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 documentation
Next.js’ example
These are sorta-kinda-OK, except…
They have to be configured per-page
They are mostly limited to queries at the top page level
You’d likely need to duplicate queries with slightly differently handling from client to server
May 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 instance
Render the page using getDataFromTree() to fill the cache with data
Render 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 up
No duplicate queries
Nothing special per page to handle server-side rendering or client-side queries.
Cache hydration to keep client active without re-querying data
Easy to enable / disable server-side rendering for individual queries
Here’s a repo with Shaw’s findings.
Sponsor: Retool
Retool, a fantastic tool for quickly building internal tools, has an even-more-fantastic program tailored to startups. If you have a startup founded less than 5 years ago with less than 10M in funding, you qualify. You’ll not only get 12 months of Retool for gree, but $160,000 of partner deals from companies like AWS, Intercom, Segment, Sentry, Digital Ocean, MongoDB, and more. Go apply!
The post 331: Next.js + Apollo + Server Side Rendering (SSR) appeared first on CodePen Blog.
