In this post, we will use Next.js and Apollo Client to create a server-rendering GraphQL Client.

View the source for this project here: https://github.com/tomanagle/apollo-example

Firstly, create a Next.js application with the npx command:

npx create-next-app apollo-example cd apollo-example yarn dev

Add all the required dependencies for the project:

yarn add @apollo/react-hooks apollo-cache-inmemory apollo-client apollo-link-http graphql graphql-tag isomorphic-unfetch next-with-apollo

Create a client configuration that we going to pass to the provider. This is where you will configure all your Apollo Client options.

Docs: https://www.apollographql.com/docs/react/api/apollo-client/

Next.js wraps your entire application in an App component to persist layout, keep state and inject additional data into your page. The component can be overwritten by created an _app.js component in your /pages directory.

Docs: https://nextjs.org/docs#custom-app

This is the perfect place to put our Apollo Provider, wrapping the entire application in the component.

Create an _app.js file in your /pages directory and add the following code:

The next step is to make a reusable query, so we can call with the useQuery hook and get the data to our page.

To create the query we will use graphql-tag, a utility for parsing GraphQL queries, mutations, and subscriptions.

Docs: https://github.com/apollographql/graphql-tag

Create a new file for your query in /graphql/jobs.query.js. Creating a single file for a query is personal preference. You can add all your queries to a single file, or create a single file for each one like I do, it’s up to you.

As queries grow in size and complexity, I find it easier to have them separated into different files. You can use a tool like GraphQL Code Generator to bundle your queries into a single, easily accessible file.

We’re going to use Apollo’s React Hooks to make our queries. It provides a nice and concise API that can call queries and mutations immediately, or lazily.

Docs: https://www.apollographql.com/docs/react/api/react-hooks/

Remove the code from your /pages/index.js and add the following:

https://gist.github.com/tomanagle/b3d99f8f9a25f86558b3b6a21d12f1b

The query hook returns an object that contains a data property, along with loading and error properties.