Can't goto SPA page route when typing route manually in Rails

Viewed 138

So far, I made the following setup:

  • Created project in Ruby on Rails 7
  • Created Vue project as a directory inside the app directory of rails
  • The Vue project is based on: Vue3, Vue-router and Vuex
  • I configured the Vue project on build to output in Rails pubic/spa directory, i.e. serve the SPA app in the static files
  • So far so good, when I run Rails and build the Vue project, everything is working as expected
  • When I click on a link on the Vue page, I'm expectedly going to the desired page
  • However, if I refresh on a routed page (e.g. spa/about) Rails throws Routing Error
  • In addition, if I try typing the route manually, I get the Routing Error again.

I'm figuring that I need a way to tell Rails to always redirect to the SPA app every time the route prefix is spa

Is there a way to config rails to do that?

something like this (in route.rb)

# every URL prefix is with spa, redirect to static file `spa/index.html`
get "spa#*" => "spa#*"
# or maybe like this?
prefix :spa # there's no `prefix` method option obviously
1 Answers

I figured it out with some digging and testing. Here's how you config Rails:

1st Create a controller with a single action

class SpaController < ApplicationController
    def index
        render file: "#{Rails.root}/public/spa/index.html", layout: false
    end
end

2nd config route.rb with the new contoller

In route.rb file, add the following line

get 'spa/*path', :to => 'spa#index'

explanation

The wild card *path is used to catch any "action" while the spa is served as my prefix as I desired in the beginning.

So for example:

  • http://localhost:3000/spa/about
  • http://localhost:3000/spa/home

All of these routes will be redirect to the same action index in my SpaController. In the case of Vue-router, it knows how to handle the routing from there.

I have not tried the same solution on other SPA frameworks (e.g. Angular), but I think this solution can work with them as well.

Happy frontend program

Related