Next.js Apollo GraphQL Client Setup

Anurag Garg
3 min readFeb 4, 2020

--

Next.js + Graphql + Apollo Client + TypeScript

GraphQL provides a complete and understandable description of the data in your API, it gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.

Building server-side rendered react website is hard, next.js commits to solving this problem beautifully. In this post, we will make a next.js app with basic auth functionality using GraphQL.

Just wanna check out the code? Help yourself ☟

So, Let’s start by creating a new app :

npx create-next-app

Folder structure

Make the following folder structure to house everything:

Dependencies

Now we will add all GraphQL dependencies required for next.js :

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

TypeScript

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.

yarn add typescript -D

The presence of a tsconfig.json file in a directory indicates that the directory is the root of a TypeScript project. The tsconfig.json file specifies the root files and the compiler options required to compile the project. A project is compiled in one of the following ways:

Using tsconfig :

  • By invoking tsc with no input files, in which case the compiler searches for the tsconfig.json file starting in the current directory and continuing up the parent directory chain.
  • By invoking tsc with no input files and a --project (or just -p) command line option that specifies the path of a directory containing a tsconfig.json file, or a path to a valid .json file containing the configurations.

tsconfig.json☟

To connect the apollo server to the client all we need is your hosted server URL and a web socket link, which in my case is:

src/config/index.ts☟

/*** Configuration*/export const SERVER = 'http://localhost:4020/graphql';export const WEB_SOCKET_LINK = 'ws://localhost:4020/graphql';

Now its time to finally start some coding. Navigate to the src folder and create a file configureClient.js where we will write all the configuration required to configure GraphQl Client

src/configureClient.ts

Now to add this configuration to your next.js app navigate to the pages folder of your project directory and create a file with name _app.tsx

Note: Filename should be perfectly the same as _app.tsx, nothing else.

_app.tsx ☟

That’s it GraphQL Apollo Client Setup is complete….🚀

Visit the below link to learn about the Server Setup ☟

--

--

Anurag Garg

Full Stack Developer | Mobile App Developer | Love to code