Configuring GraphQL Codegen
What you'll learn: How to set up codegen.yml to automatically generate TypeScript types, React hooks, and operations from your GraphQL schema and queries.
What is GraphQL Codegen Configuration?
GraphQL Code Generator reads your GraphQL schema and query documents, then transforms them into TypeScript code. The codegen.yml (or codegen.ts) file tells the generator what to generate, where to find your GraphQL files, and where to write the output.
Think of codegen.yml as a recipe card: you list your ingredients (schema and queries), specify what dish you want (types, hooks, operations), and indicate where to serve it (output directory).
Basic codegen.yml Structure
schema: "http://localhost:4000/graphql"
documents: "src/**/*.graphql"
generates:
src/generated/graphql.ts:
plugins:
- typescript
- typescript-operations
- typescript-react-apollo
This configuration does three things:
schema- Points to your GraphQL schema (URL or file path)documents- Glob pattern to find your.graphqlquery/mutation filesgenerates- Maps output files to plugins that generate code
Common Plugin Combinations
For types only:
plugins:
- typescript
For types + operations:
plugins:
- typescript
- typescript-operations
For types + operations + React hooks:
plugins:
- typescript
- typescript-operations
- typescript-react-apollo
Each plugin builds on the previous one. The typescript plugin creates base types from your schema, typescript-operations adds types for your queries and mutations, and typescript-react-apollo generates ready-to-use hooks like useGetUserQuery.
Configuration Options
config:
strictScalars: true
scalars:
DateTime: string
avoidOptionals: false
immutableTypes: true
These options control how types are generated—whether custom scalars map to TypeScript types, if optional fields use ? syntax, and if readonly modifiers are added.
Key Takeaway: GraphQL Codegen's codegen.yml file connects your schema and queries to generated TypeScript code through plugins, providing end-to-end type safety without manual type definitions.