Planning Next.js with GraphQL Codegen
I'm tackling a user's request to build a Next.js application integrated with GraphQL Code Generator for fully typed queries. They didn’t specify details, so I’ll assume the latest version of Next.js, version 14, with App Router. The plan includes steps like scaffolding the Next app, installing GraphQL dependencies like Apollo Client, setting up Code Generator packages, and creating a config file with the schema. I'll also cover adding scripts and showing an example query in React components with generated hooks and types.Creating a Direct Guide for Next.js
I need to keep things straightforward and avoid unnecessary fluff while providing a clear guide. I'll focus on using Next.js 14 with App Router and choose Apollo Client, as it has a dedicated codegen plugin for generating hooks. I'll demonstrate with a minimal example using a public schema from sources like SWAPI or Trevor Blades' API, allowing the user to run the example easily. I’ll also include setup instructions, such as using npx create-next-app@latest ..., and ensure to configure the codegen appropriately with a recommended codegen.ts file.Setting Up GraphQL Codegen Config
I’m creating a configuration for GraphQL Codegen. First, I’ll import the necessary type from the package and define my config structure. I’ll set the schema to the public endpoint at Trevor Blades’ API and point to the relevant document paths. For generation, I’m opting for the "client" preset, which supports graphql-tag out of the box. I’ll mention that while there's support for Apollo, the recommended plugins for generating hooks include typescript, typescript-operations, and typescript-react-apollo. I'll make sure to verify this against my knowledge cutoff to ensure accuracy.Considering Apollo and Typed Queries
I'm exploring how to integrate typed results using @apollo/client with TypedDocumentNode, which utilizes generics for those typed results. With Next.js 13+, server components can directly call GraphQL using fetch, simplifying things compared to Apollo. However, since the user asked for "fully typed queries," using Codegen's client preset allows us to work with the graphql tag without being tied to Apollo. I’ll mention how to install necessary packages and suggest using graphql-request or fetch in server components. This way, we can maintain typed documents for operations.Designing a GraphQL Setup with Apollo in Next.js
I’m considering how to set up GraphQL with Apollo in a Next.js application. Apollo supports typed hooks with the typescript-react-apollo plugin, making it appealing. Although Next's App Router prefers server-side calls, we can still utilize fetch for simplicity. For "fully typed queries," I can configure Codegen to create necessary types and DocumentNodes.
I'll walk through clear steps: creating the Next app, installing required dependencies, and setting up the GraphQL endpoint. I’ll establish the configuration for Codegen and the Apollo Client, ensuring we tackle SSR vs CSR appropriately while keeping the layout as clear as possible.Setting Up Apollo with GraphQL in Next.js
I’m outlining how to create an ApolloWrapper component for Next.js, which initializes an Apollo client. This involves setting up a layout to use this wrapper and creating typed queries with GraphQL Codegen. I’ll specify that the Countries List component will utilize the generated useCountriesQuery hook.
It’s essential to run codegen for type safety and ensure TypeScript recognizes the GraphQL folder in tsconfig.json. I'll also craft configurations for GraphQL Codegen, including necessary plugins and scripts for generating types and operations. Lastly, I’ll mention the command to watch for changes in queries during development. Below is a minimal, end‑to‑end example of a Next.js (App Router) app using GraphQL Code Generator to produce fully typed queries and React hooks.
Stack:
- Next.js 13/14 (App Router, TypeScript)
- Apollo Client (for queries in client components)
- GraphQL Code Generator with
typescript-react-apollo plugin
1. Create the Next.js app
npx create-next-app@latest next-graphql-codegen --ts
cd next-graphql-codegen
When prompted, you can accept the defaults.
2. Install GraphQL & Apollo dependencies
npm install graphql @apollo/client
3. Install GraphQL Code Generator & plugins
npm install -D \
@graphql-codegen/cli \
@graphql-codegen/typescript \
@graphql-codegen/typescript-operations \
@graphql-codegen/typescript-react-apollo
We’ll generate:
- Base TypeScript types (
typescript)
- Operation types (
typescript-operations)
- Typed Apollo hooks (
typescript-react-apollo)
4. Add a GraphQL query
Create a folder for GraphQL documents:
mkdir -p graphql/queries
Create graphql/queries/countries.graphql:
# graphql/queries/countries.graphql
query Countries {
countries {
code
name
capital
}
}
We’ll use the public Countries API: https://countries.trevorblades.com/.
5. Configure GraphQL Code Generator
Create codegen.ts at the project root:
// codegen.ts
import type { CodegenConfig } from '@graphql-codegen/cli';
const config: CodegenConfig = {
overwrite: true,
// Remote schema for this example:
schema: 'https://countries.trevorblades.com/',
// Where your .graphql operations live:
documents: 'graphql/**/*.graphql',
generates: {
'graphql/generated.tsx': {
plugins: [
'typescript',
'typescript-operations',
'typescript-react-apollo',
],
config: {
withHooks: true,
withHOC: false,
withComponent: false,
// optional extras:
// avoidOptionals: true,
},
},
},
};
export default config;
Add scripts to package.json:
{
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"codegen": "graphql-codegen",
"codegen:watch": "graphql-codegen --watch"
}
}
Run Codegen once:
npm run codegen
This will create graphql/generated.tsx with:
- TypeScript types for your schema
- Types for
Countries query result & variables
- A
useCountriesQuery React hook (typed!)
6. Set up Apollo Client with Next.js App Router
We’ll use a small wrapper client component so you can use Apollo hooks in any child component.
Create app/ApolloWrapper.tsx:
// app/ApolloWrapper.tsx
'use client';
import React from 'react';
import {
ApolloClient,
InMemoryCache,
ApolloProvider,
HttpLink,
} from '@apollo/client';
const client = new ApolloClient({
link: new HttpLink({
uri: 'https://countries.trevorblades.com/',
fetch,
}),
cache: new InMemoryCache(),
});
export function ApolloWrapper({ children }: { children: React.ReactNode }) {
return <ApolloProvider client={client}>{children}</ApolloProvider>;
}
Wrap your app in this provider in app/layout.tsx:
// app/layout.tsx
import './globals.css';
import type { Metadata } from 'next';
import { ApolloWrapper } from './ApolloWrapper';
export const metadata: Metadata = {
title: 'Next + GraphQL Codegen',
description: 'Example with fully typed GraphQL queries',
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<ApolloWrapper>{children}</ApolloWrapper>
</body>
</html>
);
}
layout.tsx itself remains a server component, but it renders the client ApolloWrapper that provides Apollo context.
7. Use the generated, fully typed hook in a client component
Create a client component that uses the generated useCountriesQuery hook.
// app/CountriesList.tsx
'use client';
import React from 'react';
import { useCountriesQuery } from '../graphql/generated';
export function CountriesList() {
const { data, loading, error } = useCountriesQuery();
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<ul>
{data?.countries?.map((country) =>
country ? (
<li key={country.code}>
<strong>{country.name}</strong>
{country.capital ? ` – ${country.capital}` : null}
</li>
) : null
)}
</ul>
);
}
Notes:
useCountriesQuery is auto-generated from countries.graphql.
data, loading, and error are fully typed.
data.countries and country.* fields are type-checked based on the schema.
8. Render the client component from your page
Use it in app/page.tsx (server component):
// app/page.tsx
import { CountriesList } from './CountriesList';
export default function HomePage() {
return (
<main style={{ padding: '2rem' }}>
<h1>Countries</h1>
<CountriesList />
</main>
);
}
9. Develop with auto-regenerated types
Run both the dev server and Codegen in watch mode:
# terminal 1
npm run dev
# terminal 2
npm run codegen:watch
Whenever you edit or add .graphql files under graphql/, Codegen regenerates graphql/generated.tsx, updating:
- TypeScript types for operations
- Apollo hooks like
useXxxQuery, useYyyMutation, all fully typed
10. Summary of what you get
- All GraphQL queries and mutations are declared in
.graphql files.
- GraphQL Code Generator:
- Introspects the schema (remote or local)
- Generates strict TypeScript types for results and variables
- Generates typed React hooks for Apollo (
useMyQuery, useMyMutation, etc.)
- Next.js App Router + Apollo:
- ApolloProvider via a small client wrapper
- Client components use the generated hooks
- The entire data flow is type-safe end-to-end.
If you’d like, I can also show:
- How to use the newer
client preset with a graphql() function instead of Apollo hooks, or
- How to adapt this to a self-hosted GraphQL schema (e.g., from a NestJS or Yoga server).