React Query in SSR starring Graphql-Codegen

Graphql is awesome. Need to make it more awesome?

What makes Graphql more awesome?

Imagine we query 4 properties from the type.

Now, if we can do the below, that makes working with Graphql more awesome!

In this article, we will see how to get up-to-date type checking and auto-completion with serverside data fetching synched to the client side cache.


Create a new next app.

npx create-next-app --ts

Install dependencies

npm i graphql
npm i -D @graphql-codegen/cli

Initialize the project

npx graphql-codegen init

Answer a few simple questions

Note the two plugins Typescript and Typescript Operations in Pick plugins.

Legacy peer dependency

This problem can be worked around by downgrading your npm version to 6.x. But use the --legacy-peer-deps flag.

npm i --legacy-peer-deps

Install React Query

npm i react-query
npm i -D @graphql-codegen/typescript-react-query

Update Codegen.yml

  • exposeFetcher: By default, codegen generates custom hooks for our queries and mutations. But hooks can not be used with getStaticProps or getServersideProps. This property was introduced to enable a fetcher function that we can use in the server-side functions. Ex: useGetCustomers.fetcher().
  • exposeQueryKeys: This property enables .getKey(). We use it as the key for the react query without having to manually give a string.
  • Content-Type fetchParams: The Content-Type by default is set to text/html for the response header and text/plain for the request. That will get us the POST body missing. Did you forget use body-parser middleware? error. So update this to application/json.
  • pureMagicComment: This is to enforce tree-shaking.

Sample query


npm run gql:codegen// ornpx graphql-codegen --config codegen.yml

React Query — Hydrate

We are going to use the hydration technique.

React Querying in getStaticProps

That’s it.

Try removing the client-side fetching of useGetCharacters (lines: 21, 22) and you will still see the data being stored on the client-side using the dev tools.

How cool is that?

Thank you!



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
Karthick Ragavendran

Fullstack engineer @ | React, Typescript, Redux, JavaScript, UI, Storybook, CSS, UX, Cypress, CI/CD.