The user wants a Next.js application that uses GraphQL Code Generator to create fully typed queries.
Key Requirements:
- Framework: Next.js (latest stable version is usually best, currently v14/15 with App Router is standard, but I should clarify or stick to a general implementation that works well). Let's stick to the App Router (Next.js 13+) as it's the modern standard.
- Data Source: Need a GraphQL API. For a standalone example, I should use a public API like SpaceX or Rick and Morty. SpaceX is common and simple.
- Client: I need a GraphQL client.
urql or Apollo Client are standard. urql is lightweight and great for Next.js, but Apollo is often the default mental model for many. Let's use graphql-request or urql for simplicity, or maybe Apollo if they want complex caching. Actually, urql is very "React" friendly. However, for Code Generator, the client choice matters less than the fetcher configuration. Let's stick to graphql-request for simplicity in the server component or urql for client components. Actually, the prompt implies "fully typed queries," which usually benefits heavily from a client that uses those types. graphql-request + Codegen is a very clean combination for Next.js Server Components.
- Code Generator: This is the core.
- Need
graphql-codegen/cli.
- Need plugins:
typescript, typescript-operations, typescript-graphql-request (if using that client) or typescript-react-apollo (if using Apollo). Let's go with a generic setup that generates a sdk using typescript-generic-sdk or just plain types that can be used with any fetcher.
- Decision: To make it robust, I will set up a standard Codegen flow that generates Typescript types for operations. Then I will show how to use them in a Server Component (fetching directly) or Client Component (using a client).
Plan:
- Project Initialization:
npx create-next-app@latest
- Dependencies: Install GraphQL packages (
graphql, @graphql-codegen/...).
- Configuration: Create
codegen.ts.
- Schema: Point to a public API (e.g., SpaceX).
- Queries: Create a
.graphql file with a sample query.
- Generation Script: Add script to
package.json.
- Usage in Next.js:
- Create a generated hook/type.
- Fetch data in a component.
- Display data with type safety.
Detailed Steps & Code:
-
Setup: Next.js App Router.
-
Libraries:
graphql
@graphql-codegen/cli
@graphql-codegen/typescript
@graphql-codegen/typescript-operations
@graphql-codegen/client (maybe overkill, let's stick to standard types).
@graphql-codegen/typed-document-node (This is the modern, best-practice way). It generates TypedDocumentNode which can be passed to almost any client (Apollo, Urql, graphql-request) to infer types automatically.
-
Alternative: Use typescript-graphql-request to generate a full SDK. This is often easier for beginners to understand than TypedDocumentNode. Let's do the SDK approach with graphql-request because it's very explicit.
Refining the Plan:
- Scaffold: Next.js app.
- Install:
graphql, graphql-request, @graphql-codegen/cli, typescript, typescript-operations, typescript-graphql-request.
- Config:
codegen.ts.
- Graphql:
queries.graphql.
- Run:
npm run generate.
- App: Use the generated SDK in
app/page.tsx.
Let's double check "fully typed queries".
If I use graphql-request + typescript-graphql-request plugin, it creates a class SDK.
const sdk = getSdk(client);
const data = await sdk.GetLaunches(); -> data is fully typed.
This is a very developer-friendly approach.
Structure of the Response:
- Prerequisites & Setup.
- Dependencies installation.
- GraphQL Configuration (
codegen.ts).
- Writing a Query.
- Running the generator.
- Using it in Next.js (Server Component example is hot right now, but I'll provide a generic example).
API Choice: https://spacex-production.up.railway.app/ is a standard playground API.
Step-by-step Draft:
- Step 1:
npx create-next-app@latest my-graphql-app --typescript
- Step 2: Install packages.
npm install graphql graphql-request
npm install -D @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations @graphql-codegen/typescript-graphql-request
- Step 3:
codegen.ts at root.
- Schema: url.
- Documents:
./graphql/**/*.graphql.
- Plugins: typescript, operations, graphql-request.
- Output:
./gql/ or ./src/gql/.
- Step 4: Create
graphql/launches.graphql.
- Step 5:
package.json script: "generate": "graphql-codegen"
- Step 6:
app/page.tsx.
- Import
getSdk, GraphQLClient.
- Fetch data.
- Render.
This looks solid. I will ensure to explain why we are doing this (Type safety, autocompletion).
Self-Correction during drafting:
Should I use Apollo Client?
It's heavier. For a "getting started" template, graphql-request + Codegen SDK is much cleaner and fits Next.js Server Components perfectly without complex hydration logic or providers. I will stick to graphql-request for simplicity and performance.
Wait, typescript-graphql-request is great, but sometimes generates a lot of code. Is there a simpler way?
Just generating TypedDocumentNode is the standard "modern" way.
Plugin: @graphql-codegen/typed-document-node + @graphql-codegen/typescript-operations.
Usage: import { query } from './gql'; client.request(query).
However, the SDK approach (typescript-graphql-request) gives you method names (e.g., sdk.GetUser) which feels more like a standard API service. I'll stick to the SDK approach for the "wow" factor of typing.
Let's write the response.
This guide creates a Next.js (App Router) application that integrates GraphQL Code Generator.
We will use the "SDK Plugin" approach (typescript-graphql-request). This is often preferred over Apollo Client for simple to medium apps because it generates a fully typed JavaScript function for every query (e.g., sdk.getUser()), removing the need to manually handle query strings or generic types in your components.
1. Project Setup
First, create a new Next.js project and install the necessary dependencies.
npx create-next-app@latest next-graphql-app
# Select defaults: TypeScript, ESLint, Tailwind, App Router
cd next-graphql-app
Install the GraphQL core libraries:
npm install graphql graphql-request
Install the Code Generator development tools:
npm install -D @graphql-codegen/cli @graphql-codegen/client @graphql-codegen/typescript @graphql-codegen/typescript-operations
2. Configuration
Create a codegen.ts file in your project root. This tells the generator where your GraphQL backend is, where your queries are, and what plugins to use.
File: codegen.ts
import type { CodegenConfig } from '@graphql-codegen/cli';
const config: CodegenConfig = {
// 1. The schema location (We'll use the SpaceX public API for this demo)
schema: 'https://spacex-production.up.railway.app/',
// 2. Where your frontend queries/mutations are located
documents: ['src/**/*.tsx', 'src/**/*.ts'],
// 3. Output configuration
generates: {
'./src/gql/': {
preset: 'client',
plugins: [],
},
},
ignoreNoDocuments: true, // Allows build to pass even if you have no queries yet
};
export default config;
3. Add NPM Script
Update your package.json to add a script to run the generator.
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"codegen": "graphql-codegen --config codegen.ts"
},
4. Create a GraphQL Query
We will create a "Fragment" and a "Query" inside a TypeScript file. Code Generator will scan this file, extract the GraphQL strings, and generate types for them.
File: src/queries.ts
import { gql } from 'graphql-request';
// Defining a fragment ensures your types are generated for sub-selections
export const LaunchFragment = gql`
fragment LaunchFragment on Launch {
id
mission_name
launch_date_utc
rocket {
rocket_name
}
launch_success
}
`;
// The main query to fetch past launches
export const GetLaunchesDocument = gql`
query GetLaunches($limit: Int!) {
launches_past(limit: $limit) {
...LaunchFragment
}
}
`;
5. Run the Generator
Run the command to generate the types. This will create a folder at src/gql/ containing all your types and a ready-to-use SDK.
npm run codegen
Note: You should run this command every time you change your queries.
6. Create the API Client
To make this clean, we will create a reusable API client that wraps the generated SDK.
File: src/lib/api.ts
import { GraphQLClient } from 'graphql-request';
import { getSdk } from '@/gql/sdk'; // This file is generated
// Initialize the client with the API URL
const client = new GraphQLClient('https://spacex-production.up.railway.app/');
// Export the fully typed SDK
export const sdk = getSdk(client);
7. Usage in a Next.js Server Component
Now we can use our fully typed sdk inside a Next.js Page. Because graphql-request returns a Promise, this works perfectly with Next.js async Server Components.
File: src/app/page.tsx
import { sdk } from '@/lib/api';
import { LaunchFragment } from '@/gql/graphql'; // Import generated types
// This component receives fully typed props
const LaunchCard = ({ launch }: { launch: LaunchFragment }) => {
return (
<div className="p-4 border rounded-lg shadow-sm bg-white mb-4">
<div className="flex justify-between items-center">
<h2 className="text-xl font-bold text-gray-800">{launch.mission_name}</h2>
{/* TypeScript knows these properties exist and their types */}
<span
className={`px-2 py-1 text-xs rounded-full font-medium ${
launch.launch_success
? 'bg-green-100 text-green-800'
: 'bg-red-100 text-red-800'
}`}
>
{launch.launch_success ? 'Success' : 'Failed'}
</span>
</div>
<div className="mt-2 text-sm text-gray-600">
<p>Rocket: {launch.rocket?.rocket_name}</p>
<p>Date: {new Date(launch.launch_date_utc).toLocaleDateString()}</p>
</div>
</div>
);
};
// The Page is an async Server Component
export default async function Home() {
try {
// Call the generated SDK method.
// Arguments are fully typed! (limit must be a number)
const data = await sdk.GetLaunches({ limit: 10 });
return (
<main className="min-h-screen p-8 bg-gray-50">
<div className="max-w-2xl mx-auto">
<h1 className="text-3xl font-bold mb-6 text-gray-900">SpaceX Launches</h1>
<div className="space-y-4">
{data.launches_past?.map((launch) => (
launch && <LaunchCard key={launch.id} launch={launch} />
))}
</div>
</div>
</main>
);
} catch (error) {
return <div className="p-8 text-red-500">Error loading launches</div>;
}
}
Summary of Workflow
- Write Query: You write a query in
queries.ts.
- Generate: You run
npm run codegen.
- Consume: You import
sdk and call methods like sdk.GetLaunches(). The return data is automatically inferred by TypeScript.
Best Practices
- VS Code Extension: Install the "GraphQL" extension by GraphQL Foundation. It will syntax highlight your
gql tags and provide intellisense based on your schema.
- Watch Mode: During active development, you can run the generator in watch mode so it updates types as you type queries:
npm run codegen -- --watch
- Strict Typing: Notice in
LaunchCard we typed the prop as LaunchFragment. This type was auto-generated based on the GraphQL fragment you defined, ensuring your UI exactly matches the data you requested.