Rails special route for single page applications

goncalvesjoao
2 min readApr 7, 2016

OK. You got a React, Angular, Ember, etc. Single Page Application (SPA) with its own set of routes.

You also have a Rails app with its own set of routes, integrated with your SPA.

Every time a request does not match a Rails route you need it to return an index.html file that loads your SPA, so that your SPA route system can decided whether or not that request is a real 404.

Line 18 does just that. Great, but…

Now every time your SPA makes a request, say “/api/v1/heroess.json” that should return a 404 with a json response, you’ll get a 200 with your SPA index.html.

So, in truth you just want to return your SPA index.html when you make a html non xhr request. What does that mean?

Browser native requests for html pages, only.

So, Ajax requests should not be intercepted and requests for any other type of format besides html should too.

Rails Routing from the Outside In” talks about the constraints option, but must of us just remember the constrain by regex approach.

Now a GET browser request for:

  • “/users” will return a 200 OK
  • “/userss” will return a 200 OK with your SPA index.html that will decide if that’s a 404 request
  • “/userss.html” will also return your SPA
  • “/userss.json” will return a 404 Not Found (yay!)

and any Ajax request will ignored by the line 18 route, cool.

--

--

goncalvesjoao

Been developing for the web since 2007, went to London in 2016, moved to Tokyo in 2017 and now I’m back to Portugal.