How to setup Apollo Client to perform GraphQL queries with NextJS

Oleksandr Hrishchuk
2 min readJun 10, 2020

In the previous article Setting up GraphQL API with MongoDB and Apollo Server for a NextJS app we’ve created a GraphQL API with Apollo Server setup and connection to the MongoDB. We worked mainly on the server-side of the application.

It’s recommended to read and follow along the first part if you haven’t.

In this article, we’re moving to the client-side of the application and we’ll learn how to consume an API that we’ve created in the first part. Meaning, performing queries from our NextJS application to the GraphQL API.

An idea

To perform queries to our GraphQL API from the client-side (and not only from the GraphQL Playground), we’ll need to set up Apollo Client.

Using a custom implementation of the withApollo() high-order component we are going to wrap index file with it and make queries to the API.

yarn add apollo-client @apollo/react-hooks @apollo/react-ssr apollo-cache-inmemory apollo-link-http apollo-link-schema graphql-tag

Setting up an Apollo Client

At the project root let’s create a folder called apollo/ with a client.js file inside.

Sharing schema between Apollo Client and Apollo Server

Our GraphQL schema is located now under the pages/api/graphql.js alongside with our Apollo Server setup.

Before we had all the setup in on file on the server, like so:

However, we need to access schema on the client-side as well so let’s move typeDefs, resolvers and schema setup to the apollo folder on the client and just import it on the server.

Inside the apollo/ folder let's create type-defs.js, resolvers.js and schema.js files and move respective parts in there so you would have a file structure like this:

After moving files to the client our Apollo Server setup looks nice and clean:

After the refactoring our API still works as expected:

Create Users component and perform queries to the GraphQL API

Create components/Users.js component which will display a list of users:

Wrap Index file withApollo() HOC

In order for GraphQL Queries to work, we need to wrap our Index page withApollo() HOC.

Let’s refactor our Index page to display the Users component and import withApollo().

That’s it! We can perform queries to our GraphQL API with Apollo Client and fetch data from MongoDB.

I created a supporting repository for this article so you can follow along commit-by-commit. See deployed project preview here

Originally published at https://grischuk.de on June 10, 2020.

--

--

Oleksandr Hrishchuk

Software Engineer living and working in Berlin. #react #redux #graphql #nodejs Blog: https://oleks.pro/ GitHub: https://github.com/alexandr-g