Framing the Objective
I'm currently focused on defining the core goal: building a Next.js application. It will use GraphQL for data retrieval, and I intend to employ GraphQL Code Generator. This approach should guarantee TypeScript type safety for queries, mutations, and all related operations.
Outlining the Structure
Now I'm designing the architecture. I've decided on Next.js with the App Router, using TypeScript for type safety, and Apollo Client for the GraphQL interaction. To demonstrate code generation, I'll leverage the Countries API. I'm focusing on simplicity, using Client Components for basic fetches to showcase Codegen most effectively.
Detailing the Steps
I'm deep in the process of mapping out the build guide's steps. I've broken down each phase, like setting up Next.js and installing dependencies. A key decision is how to structure GraphQL operations using the client-preset, which I'll highlight for the best developer experience. Configuring Apollo Client with the App Router is also a key task that needs to be addressed.
Developing the Structure
Now, I'm fleshing out the guide's content. I'm focusing on the configuration of GraphQL Code Generator using the client-preset, a key factor for a good developer experience. I've also decided to use the Countries API, ensuring it's straightforward and doesn't require extra steps like API keys. I'm also finalizing how the example query will be written.
Revising Component Strategy
I've re-evaluated the component approach. To simplify and focus on Codegen, a Client Component will be best, showcasing Apollo hooks. I will now integrate the useQuery hook with the generated types. This will require some basic Apollo Client setup, but avoids unnecessary complexity.
Clarifying the Approach
I'm now revisiting the component choice. While a Server Component with client-side fetching could work, a Client Component with useQuery best showcases the type-safety benefits of Codegen in an interactive way. I will incorporate Apollo Client's Provider to ensure it works correctly and keep the example clear and concise.
Developing the Structure and Code
I'm now drafting the component, the core of the tutorial. This involves setting up the Apollo Client provider, followed by the query itself. I will show how to display the typed data from the useQuery hook. I'm focusing on simplicity with a Server Component and simple fetches using the typed SDK, as this best reflects the user's needs.
This guide will walk you through building a Next.js (App Router) application configured with Apollo Client and GraphQL Code Generator.
We will use the client-preset from GraphQL Codegen. This is the modern, recommended approach. It generates a specialized gql function that automatically infers TypeScript types for your queries and their results, eliminating the need to manually import types.
Prerequisites
Step 1: Setup Next.js Application
Initialize a new Next.js app with TypeScript.
npx create-next-app@latest my-graphql-app
# Select Yes for: TypeScript, ESLint, Tailwind CSS, App Router
# Select No for: src directory (optional, but this guide assumes 'src' or root)
Enter the project directory:
cd my-graphql-app
Step 2: Install Dependencies
Install Apollo Client and GraphQL packages:
npm install @apollo/client graphql
Install GraphQL Code Generator dev dependencies:
npm install -D @graphql-codegen/cli @graphql-codegen/client-preset @parcel/watcher
Step 3: Configure Code Generator
Initialize the configuration file. You can run npx graphql-codegen init, but it is often cleaner to create the file manually to ensure the configuration is exact for Next.js.
Create a file named codegen.ts in your root directory:
import type { CodegenConfig } from '@graphql-codegen/cli';
const config: CodegenConfig = {
overwrite: true,
schema: "https://countries.trevorblades.com", // The GraphQL API URL
documents: ["src/**/*.tsx", "src/**/*.ts"], // Where your queries will be written
ignoreNoDocuments: true, // don't error if we haven't written a query yet
generates: {
"./src/gql/": {
preset: "client",
presetConfig: {
gqlTagName: "gql",
}
}
}
};
export default config;
Add a script to package.json to run the generator:
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"codegen": "graphql-codegen --watch"
}
Step 4: Setup Apollo Client Provider
Since we are using Next.js App Router, we need to wrap our application in a Provider to use Apollo hooks (like useQuery) in Client Components.
Create the file src/lib/apollo-wrapper.tsx:
"use client";
import {
ApolloLink,
HttpLink,
} from "@apollo/client";
import {
ApolloNextAppProvider,
NextSSRApolloClient,
NextSSRInMemoryCache,
SSRMultipartLink,
} from "@apollo/experimental-nextjs-app-support/ssr";
// Note: You might need to install this experimental package for App Router SSR support
// or just use standard ApolloProvider for pure Client Side Rendering.
// For simplicity in this tutorial, we will use the standard @apollo/client setup
// tailored for Client Components.
import { ApolloClient, InMemoryCache, ApolloProvider } from "@apollo/client";
const client = new ApolloClient({
uri: "https://countries.trevorblades.com",
cache: new InMemoryCache(),
});
export function ApolloWrapper({ children }: { children: React.ReactNode }) {
return (
<ApolloProvider client={client}>
{children}
</ApolloProvider>
);
}
Update your Root Layout in src/app/layout.tsx:
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import { ApolloWrapper } from "../lib/apollo-wrapper"; // Import wrapper
const inter = Inter({ subsets: ["latin"] });
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body className={inter.className}>
{/* Wrap children with ApolloWrapper */}
<ApolloWrapper>{children}</ApolloWrapper>
</body>
</html>
);
}
Step 5: Write a Query & Generate Types
-
Start the codegen watcher in a separate terminal. This will watch your files and generate types immediately when you save a query.
npm run codegen
-
Create a Client Component to display data. Create src/components/CountriesList.tsx.
Crucial: Do not import gql from @apollo/client. Import it from your generated src/gql folder.
"use client";
import { useQuery } from "@apollo/client";
import { gql } from "../gql"; // This is the magic generated import!
// Define query using the generated 'gql' function
const GET_COUNTRIES = gql(`
query GetCountries {
countries {
code
name
emoji
capital
}
}
`);
export default function CountriesList() {
// data is fully typed automatically!
const { data, loading, error } = useQuery(GET_COUNTRIES);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 p-4">
{data?.countries.map((country) => (
<div key={country.code} className="border p-4 rounded shadow">
<div className="text-2xl">{country.emoji}</div>
<h3 className="font-bold text-lg">{country.name}</h3>
<p className="text-gray-600">Capital: {country.capital}</p>
</div>
))}
</div>
);
}
Note: If npm run codegen is running, as soon as you save this file, it detects the gql string and updates the types in src/gql.
Step 6: Use the Component
Update src/app/page.tsx:
import CountriesList from "../components/CountriesList";
export default function Home() {
return (
<main className="min-h-screen p-8">
<h1 className="text-4xl font-bold mb-8 text-center">
Next.js + GraphQL Codegen
</h1>
<CountriesList />
</main>
);
}
Step 7: Verification
- Run the development server:
npm run dev
- Open
http://localhost:3000.
How to verify Type Safety?
Go back to src/components/CountriesList.tsx and try to access a property inside the map function that you did not request in the query (e.g., country.currency).
// TypeScript Error!
// Property 'currency' does not exist on type '{ __typename?: "Country" | undefined; code: string; name: string; emoji: string; capital?: string | null | undefined; }'.
console.log(country.currency);
Summary of the Workflow
- Write Query: Write your GraphQL query inside a
gql(\...`)` tag in your component.
- Codegen Watch: The
npm run codegen script detects the change.
- Auto-Type: The
client-preset updates the src/gql folder.
- Result: The
useQuery hook infers the exact shape of your data. You explicitly know if a field is nullable, an array, or a string.