Urql with Next.js & Sanity
πŸŽ‰

Urql with Next.js & Sanity

Created
Mar 26, 2022 04:44 AM
Author
Tags

Installing dependencies

Install the following

URQL dependencies

yarn add next-urql react-is urql graphql
OR
npm install --save next-urql react-is urql graphql

GraphQL dependencies

yarn add graphql graphql-tag

Intialising URQL provider

Now we have our packages installed we have to connect to our API with URQL and allow our app context of the provider. To do so we initialise the URQL provider at the base of the apps render cycle ./pages/_app.tsx which wraps around all components
import { cacheExchange, dedupExchange, fetchExchange } from "urql"; import type { AppProps } from "next/app"; import { withUrqlClient } from "next-urql"; const App = ({ Component, pageProps }: AppProps) => { return <Component {...pageProps} />; } export default withUrqlClient( (ssrExchange) => ({ url: `https://${process.env.SANITY_SPACE_ID}.api.sanity.io/v1/graphql/dev/default`, fetchOptions: () => { const token = process.env.SANITY_API_KEY; return { headers: { Authorization: token ? `Bearer ${token}` : "" }, }; }, exchanges: [dedupExchange, cacheExchange, ssrExchange, fetchExchange], }), { ssr: true } )(App);
πŸ’‘
Note this is using the dev dataset Also you will have to set SANITY_SPACE_ID & SANITY_API_KEY in your .env file
Β 
Some points to also note on the client initialisation
  • It is fetching data server side as { ssr: true } this is due to it requiring the environment varibles only available server side. If you want your Urql client side then the API must be public or have a client side method of authentication.
  • You can change the url param to any API of your choosing, for this tutorial however make sure it is a graphQL endpoint

Setting up GraphQL Queries

Now that we have set up Urql you may be itching to write queries but we need to quickly do some config so typescript understands how to handle .graphql files
Β 
In your base directory of you project create a file graphql.d.ts with the following content
declare module "*.graphql" { import { DocumentNode } from "graphql"; const Schema: DocumentNode; export = Schema; }
We also need to add the following to our next.config.js file
/** @type {import('next').NextConfig} */ module.exports = { reactStrictMode: true, // other config // ONLY CODE BELOW REQUIRED ----------- webpack: (config) => { config.module.rules.push({ test: /\.(graphql|gql)$/, exclude: /node_modules/, loader: 'graphql-tag/loader', }); return config; }, webpackDevMiddleware: (config) => { return config; }, // ------------------------------------- }
Β 

Extra! GraphQL Schema Generation

install the following deps
npm i @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations @graphql-codegen/typescript-react-query
Β 

Caching FTW!

install caching for urql with the following
npm install --save @urql/exchange-graphcache
Then simply add the following code to your client provider initialiser.
import { createClient, dedupExchange, fetchExchange } from 'urql'; import { cacheExchange } from '@urql/exchange-graphcache'; // ./pages/_app.tsx export default withUrqlClient( (ssrExchange) => ({ url: `https://${process.env.SANITY_SPACE_ID}.api.sanity.io/v1/graphql/dev/default`, fetchOptions: () => { const token = process.env.SANITY_API_KEY; return { headers: { Authorization: token ? `Bearer ${token}` : "" }, }; }, exchanges: [dedupExchange, cacheExchange({}), ssrExchange, fetchExchange], }), { ssr: true } )(App);
Β