Actually it’s not so much about Rails, but about JSON API. So if you don’t use/like Rails, just take it as an abstract API and keep reading.
I’ve been trying to implement JS server rendering within Rails app using react-rails gem, but it’s not the way to go. Tools plays best in environments, for which they were designed. So I cut whole front-end stuff out of Rails and moved it to Node.js.
Here is the first draft:
Let’s go deeper. When user hits http://my-app.com, request goes to the Node.js server with Express on top. We need the data to render initial html and send the response. So we fetch it from Rails API via http-request. When the data is arrived, React renders the view and Express sends html to the user with client JS app, which takes control over the flow. When the user hits some link on the site, app makes the ajax call to fetch the new data and updates the views on the client.
Front-end app lives on the main domain — http://my-app.com. But for the API we have an options:
We can have it on the same domain, but on the different port. Then we are forced to keep 2 apps on the same server.
I prefer another option — put it on the subdomain (or another domain), so we can scale app in the future without changing the codebase.
Next we need to decide how we’ll be getting the data from API via ajax requests.
Option 1. Ajax CORS requests
Because of the same-origin policy we can’t make ajax requests from one location to another (even if the target resource on the same domain but different port). To enable such kind of requests we need to apply Cross-Origin Resource Sharing (CORS) mechanism.
If you’ll chose to go this way, you’ll need to set special http-headers on the Rails side. This way browser is verifying that caller have the rights to send the ajax requests to this server.
In application_controller.rb do something like this: