How to setup Apollo Client to perform GraphQL queries with NextJS

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 high-order component we are going to wrap index file with it and make queries to the API.

Setting up an Apollo Client

At the project root let’s create a folder called with a file inside.

Sharing schema between Apollo Client and Apollo Server

Our GraphQL schema is located now under the 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 , and setup to the folder on the client and just import it on the server.

Inside the folder let's create , and 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 component which will display a list of users:

Wrap Index file HOC

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

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

That’s it! We can perform queries to our GraphQL API with Apollo Client and fetch data from the 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.

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store