CodePen Radio

331: Next.js + Apollo + Server Side Rendering (SSR)

09.01.2021 - By CodePen BlogPlay

Download our free app to listen on your phone

Download on the App StoreGet it on Google Play

Our goal here was to explore server-side rendering (SSR) in Next.js using data from Apollo GraphQL, for faster client-rendering and SEO benefits.

There are a variety of approaches, but Shaw has set his sights on a very developer-ergonomic version here where you can leave queries on individual components and mark them as SSR-or-not.

There are two "official" approaches:

Apollo's documentationNext.js' example

These are sorta-kinda-OK, except...

They have to be configured per-pageThey are mostly limited to queries at the top page levelYou'd likely need to duplicate queries with slightly differently handling from client to serverMay or may not populate the client cache so that the client can have live queries without having to query for the same data. For example, ay you have data that you want to change on the client side (pagination, fetching new results). If it's fetched and rendered server-side, you have to fetch again client side or send over the cache from the server so the queries on the client-side can be ready to update with new data.

These limitations are workable in some situations, but we want to avoid duplicating code and also have server-side rendered queries that aren't top-level on the page.

A probably-better approach is to use the getDataFromTree method, which walks down the tree and executes the queries to fill up the ApolloClient cache. We got this from a two-year old Gist from Tylerian showing a way to integrate getDataFromTree into Next.js. Tylerian's gist had some extra complications that might've been due to older Next.js limitations, but the overall process was sound:

Create a shared ApolloClient instanceRender the page using getDataFromTree() to fill the cache with dataRender the page again with that data using Next's Document.getInitialProps()Extract the cache to deliver with the page and hydrate the client-side Apollo cache

The benefits:

Quick to set upNo duplicate queriesNothing special per page to handle server-side rendering or client-side queries.Cache hydration to keep client active without re-querying dataEasy to enable / disable server-side rendering for individual queries

Here's a repo with Shaw's findings.

More episodes from CodePen Radio