@graphql-codegen/cli to generate TypeScript types and typed document nodes directly from the backend GraphQL schema. This means you never write GraphQL response types by hand — they are always in sync with the actual schema.
How it works
- The codegen tool connects to the running backend at
http://localhost:8000/graphql/(orPUBLIC_API_URLif overridden). - It first fetches a CSRF token from
/csrf/to authenticate the schema introspection request. - It introspects the live schema and scans all
*.tsand*.tsxfiles insrc/for GraphQL operation definitions (queries, mutations, fragments). - It generates TypeScript types and TypedDocumentNode objects into
src/types/__generated__/.
Output
Generated files are written tosrc/types/__generated__/. The main file is:
Configuration
The codegen configuration lives infrontend/graphql-codegen.ts. Key settings:
Scalar mappings
Custom scalar types are mapped to TypeScript types in the config:| GraphQL scalar | TypeScript type |
|---|---|
Date | string | number |
DateTime | string | number |
JSON | Record<string, unknown> |
Nullable fields
The config setsavoidOptionals.field: true, which means nullable GraphQL fields are typed as T | null rather than T | undefined. This matches Apollo Client’s runtime behaviour.
Running the codegen
Start the backend
The codegen connects to a live backend to introspect the schema. Make sure the backend is running:Or start the backend on its own if you have it set up directly.
Run the codegen command
From the This runs
frontend/ directory:graphql-codegen --config graphql-codegen.ts.Regenerating types after schema changes
Whenever the backend GraphQL schema changes (new types, updated fields, renamed operations), regenerate the types:src/types/__generated__/ alongside any code changes that depend on the new schema.
Overriding the backend URL
If your backend runs on a different port or host, set thePUBLIC_API_URL environment variable before running the codegen:
