/next-apollo-ssr

Server-side rendering with Next.js and Apollo GraphQL

Primary LanguageJavaScript

Next.js & Apollo GraphQL Server-Side Rendering

The recommended Apollo method for Server-Side Rendering in Next.js involves duplicating queries, separate code for server and client, and a bunch of added complications.

This approach uses built-in methods from Next.js and Apollo to server-side render GraphQL queries and fill the Apollo Cache so the client doesn't have to refetch the data.

See comments in _document.js and _apollo.js for the most important bits.

Advantages

  • Relatively simple to implement
  • Query as normal with useQuery; no duplication or special methods for SSR queries
  • No special client-side detection/rendering needed in most cases
  • Cache hydration so the client doesn't have to re-query data the server already fetched, but the client-side query & data will update properly with changes.
  • Can enable/disable SSR for all queries (ApolloClient defaultOptions) or only certain ones ( useQuery(..., { ssr: true|false }) ) to optimize page delivery

Demo:

References:

To run this example:

  • npm install or yarn
  • npm run dev or yarn dev