Overview
To view this content, get the Pro package! 😃🙏
Or if you’ve already purchased.
Server-Side Rendering
Chapter contents:
Background: SSR, Node, HTTP, Server, and the React chapter
As we mentioned in Background > SSR, server-side rendering often results in faster load times. But if we render our app on the server the same way we render on the client, then all our Apollo Client queries will be in the loading state, and the HTML the server sends to the client will have loading spinners and skeletons everywhere. In most cases, we want the HTML to contain all the GraphQL data from the completed queries, so that the client sees the data immediately. We can do this in six steps:
- Apollo Client makes all queries in our app and waits for them to complete.
- Once complete, we render the app to HTML.
- We get the current state of the Apollo cache.
- We create an HTML document that contains both #2 and #3.
- We send it to the client.
- When the page loads on the client, we create an instance of
ApolloClient
with the #3 cache data.
There are some differences in the API for parts of this process, depending on which view library we’re using. Here are links to the documentation for React Apollo SSR, Vue Apollo SSR, and Apollo Angular SSR.
In this chapter, we’ll use the React version as the example API. We’ll base our code off the Chapter 6: React repository, but we won’t cover all the steps, like matching what Create React App is doing for us with Babel, asset loading, etc. If you think you might want SSR when starting a project, we recommend using Next.js or Gatsby instead of CRA (which doesn’t support SSR). Here’s a starter template for Next.js and a theme for Gatsby.