Rails 5 api only app with home page
I was in the same boat, trying to do a Rails 5 API app that could still bootstrap from a single html page (taken over by JS on load). Stealing a hint from rails source, I created the following controller (note that it's using Rails' instead of my ApplicationController
for this lone non-api controller)
require 'rails/application_controller'
class StaticController < Rails::ApplicationController
def index
render file: Rails.root.join('public', 'index.html')
end
end
and put the corresponding static file (plain .html
, not .html.erb
) in the public
folder. I also added
get '*other', to: 'static#index'
at the end of routes.rb
(after all my api routes) to enable preservation of client-side routing for reloads, deep links, etc.
Without setting root in routes.rb
, Rails will serve directly from public on calls to /
and will hit the static controller on non-api routes otherwise. Depending on your use-case, adding public/index.html
(without root in routes.rb
) might be enough, or you can achieve a similar thing without the odd StaticController
by using
get '*other', to: redirect('/')
instead, if you don't care about path preservation.
I'd love to know if anyone else has better suggestions though.