Think carefully about whether you need server-side rendering. If you don’t really need it I wouldn’t recommend implementing it, even if it is all the rage these days.
If you’re not sure whether you need server-side rendering (SSR), here’s my quick list:
DO use server-side rendering…
- if you need SEO on non-Google search engines
- if you have a large application and need to reduce time to first render for UX
DO NOT use server-side rendering…
- if you’re ok with just Google SEO
This article is focused on developing a universal GraphQL/Relay application in particular. If that’s your situation, great! If not, I highly recommend you check out GraphQL. If you decide GraphQL fits your needs, you can get started with Choosing a GraphQL Client.
If all you wanted to see was code, here. This is a sample full-stack Relay project using isomorphic-relay-router. It’s available on GitHub to serve as an example for the rest of this post.
There’s really not much that has to change in order to use isomorphic-relay-router on top of a Relay app using react-router-relay. It’s fairly similar to upgrading a plain React app using react-router to a universal React app. Here’s the general process:
isomorphic-relayallows us use Relay universally
isomorphic-relay-routerallows us to render Relay components on both the server and client
ejsis our server-side template rendering engine
2. Let’s start with setting up the template (with
ejs) for our server to render. If we had an
index.htmlfile, or equivalent, we can remove that now. Our
index.ejs file will look almost the same as the html file except for the parts that load the server-rendered react component and the data.
3. If your react-router routes aren’t already in a separate file, now would be a great time to move them. We need our routes to live in a separate file because they’ll be needed both server and client side in order to render the correct component.
4. In the
server/index.js file that holds the endpoints for our app, we need to add the isomorphic route. We specify the network layer for Relay, use react-router’s
match function. If you’re not familiar with server-side rendering with react-router, you can find a little more info on their docs.
5. Lastly, we need to set up the client side to receive the server-rendered template with data. Again, we set the network layer for Relay, use react-router’s match function to render the right component, and render with ReactDOM this time.
6. Congratulations! That’s it. The app should still function the same as before. As a sanity check, you can see if the sources look like what you expect in the developer console of your favorite browser. In my example, there’s the index file that was rendered by the server using the ejs template.
For more info about the starter kit used as an example in this post, check out my colleague’s article on Strategies for Creating a Web Application Starter Kit.
Check out more technical blogs on our website.