React Query in SSR starring Graphql-Codegen
Graphql is awesome. Need to make it more awesome?
What makes Graphql more awesome?
Consider the below type
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.
Find the repository for finished code below.
Create a new next app.
npx create-next-app --ts
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 Operations in
Legacy peer dependency
While installing the dependencies with
npm i, You may encounter the
Could not resolve dependency problem with the version of
This problem can be worked around by downgrading your npm version to
6.x. But use the
npm i --legacy-peer-deps
Install React Query
The official documentation of
graphql-codegen plugin for the
react-query is elaborate. Check that out for more details.
npm i react-query
npm i -D @graphql-codegen/typescript-react-query
Update the codegen.yml file in the root to resemble the below.
exposeFetcher: By default, codegen generates custom hooks for our queries and mutations. But hooks can not be used with
getServersideProps. This property was introduced to enable a fetcher function that we can use in the server-side functions. Ex:
exposeQueryKeys: This property enables
.getKey(). We use it as the key for the react query without having to manually give a string.
Content-TypefetchParams: The Content-Type by default is set to
text/htmlfor the response header and
text/plainfor the request. That will get us the
POST body missing. Did you forget use body-parser middleware?error. So update this to
pureMagicComment: This is to enforce tree-shaking.
query.graphql file. You can name this anything you want as long as it matches
src/**/*.graphql that we provided in the documents field in codegen.yml.
Execute the below command to see your types and react query hooks generated for us!
npm run gql:codegen// ornpx graphql-codegen --config codegen.yml
React Query — Hydrate
React query suggests two ways to query data in SSR. Read about that in detail here.
We are going to use the
React Querying in getStaticProps
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?