Course contentsShow
← TypeScript
Lesson 1313 of 1,79630. Type-Safe APIsFree lesson

GraphQL Code Generation with graphql-codegen

Automatically generating TypeScript types from GraphQL schemas and queries for complete type safety.

GraphQL Code Generation with graphql-codegen

You'll learn: How to automatically generate TypeScript types from your GraphQL schemas and queries, creating complete type safety between your frontend and backend.

The Manual Typing Problem

When working with GraphQL APIs, you typically write queries in .graphql files or template strings, then manually create TypeScript interfaces that match the expected response shape. This creates a dangerous gap: your types might not match what the API actually returns, and when the schema changes, your types don't automatically update.

What graphql-codegen Does

The @graphql-codegen/cli tool reads your GraphQL schema and your query documents, then generates TypeScript types that perfectly match both. It creates:

  • Type definitions for every query, mutation, and subscription
  • Input types for variables
  • Fragment types for reusable query pieces
  • Full schema types for your entire API

Think of it as a bridge builder between your GraphQL schema (the API contract) and your TypeScript code (the consumer). The bridge automatically rebuilds whenever either side changes.

The Workflow

You define a codegen.yml configuration file specifying where your schema lives (a URL, local file, or introspection result), where your queries are (.graphql files or inline in .ts files), and where to generate types. Running graphql-codegen produces type files you import alongside your queries, giving you autocomplete and compile-time errors if you access non-existent fields or pass wrong variable types.

This eliminates the duplication problem from earlier lessons—your schema becomes the single source of truth, just like with Zod or OpenAPI, but specifically for GraphQL.

Key Takeaway: GraphQL Code Generator closes the type safety gap between GraphQL schemas and TypeScript clients by automatically generating types from your actual API contract, making impossible states unrepresentable at compile time.