GraphQL Type-Safe Client Generation: A Practical Guide

Learn how GraphQL type-safe client generation turns schemas and operations into reliable TypeScript types, with setup guidance and CI best practices.

ASOasis
7 min read
GraphQL Type-Safe Client Generation: A Practical Guide

Image used for representation purposes only.

What Is GraphQL Type-Safe Client Generation?

GraphQL type-safe client generation turns a GraphQL schema and the operations your application actually uses into TypeScript artifacts. Those artifacts describe each operation’s result and variables, so your editor and compiler can catch many mistakes before a request reaches the server.

The key idea is to generate types from operations, not just from the schema. A schema may define hundreds of fields, but a particular query selects only a few. Operation-based types model that selection set, including nested fields and nullability, so client code can work with the response shape it requested. GraphQL Code Generator’s client preset is one widely used, framework-independent approach, and its generated typed documents can be consumed by compatible clients such as Apollo Client and urql. (the-guild.dev )

How the Generation Pipeline Works

A typical setup has four inputs and steps:

  1. A schema: A local .graphql file, a schema downloaded from your API, or another schema source. GraphQL introspection can expose an API’s types and fields to development tools, though teams may choose to distribute a schema file instead. (graphql.org )
  2. Operations: Queries, mutations, subscriptions, and fragments written in .graphql files or embedded in TypeScript.
  3. Code generation: A CLI reads the schema and operations, checks that the operations are valid, and writes generated artifacts.
  4. Typed execution: The application passes a generated typed document to a compatible GraphQL client. TypeScript can infer the expected variables and result types from that document. (github.com )

This creates a useful feedback loop: edit an operation, regenerate its artifacts, and let the compiler show where application code needs to change. Generated output should be treated as build output rather than hand-maintained source.

A Practical Setup with GraphQL Code Generator

The following example uses the Code Generator client preset. Install the CLI and preset as development dependencies, then add a codegen.ts configuration file. The preset is designed to generate typed client operations without requiring a particular UI framework. (the-guild.dev )

npm install --save-dev @graphql-codegen/cli @graphql-codegen/client-preset
// codegen.ts
import type { CodegenConfig } from '@graphql-codegen/cli'

const config: CodegenConfig = {
  schema: './schema.graphql',
  documents: ['src/**/*.{ts,tsx,graphql}', '!src/gql/**'],
  generates: {
    './src/gql/': {
      preset: 'client',
    },
  },
}

export default config

The schema entry points to the API schema, while documents tells the generator where to find application operations. Excluding the output directory prevents generated files from being scanned as inputs. Run generation from the command line, and consider adding the command to package.json:

npx graphql-codegen --config codegen.ts

For local development, Code Generator also supports watch mode, which regenerates artifacts as relevant files change. (the-guild.dev )

Now define an operation through the generated graphql helper:

import { graphql } from './gql'

export const ProductQuery = graphql(/* GraphQL */ `
  query Product($id: ID!) {
    product(id: $id) {
      id
      name
      price
    }
  }
`)

A compatible GraphQL client can infer both the response and variables from ProductQuery. For example, passing a number where the schema requires an ID-compatible value, omitting a required variable, or accessing a field that was not selected can produce a TypeScript error. The precise ID representation depends on your generator configuration and scalar mapping; GraphQL Code Generator v6 documents string | number as its default TypeScript representation for the built-in ID scalar. (apollographql.com )

What Gets Typed—and What Does Not

Generated operation types can cover:

  • Variables: required and optional inputs, including nested input objects.
  • Results: the fields selected by an operation, with nested objects and schema nullability represented in TypeScript.
  • Fragments: shared selections that can be composed into operations.
  • Typed documents: operation documents that carry result and variable type information for compatible client APIs. (the-guild.dev )

This is compile-time safety, not proof that every network response is valid. Type generation does not by itself check authorization, business rules, resolver behavior, or whether a production server is running the same schema snapshot used to generate the types. It also does not validate untrusted JSON at runtime. If runtime validation is required—for example, when consuming a third-party API with uncertain deployment consistency—add an explicit validation step at the network boundary.

Choosing a Generation Strategy

For most TypeScript front ends, begin with the client preset. It packages recommended operation-focused generation and works with different client libraries rather than tying generated types to a single UI framework. The generated TypedDocumentNode lets supported clients infer types from the document instead of requiring developers to repeatedly specify result and variable generics. (the-guild.dev )

A custom plugin configuration may be appropriate when a repository has established conventions, produces SDKs for multiple languages, or needs distinct outputs for separate application domains. GraphQL Code Generator is plugin-based and supports a range of outputs, but every additional customization increases the configuration and maintenance surface. (the-guild.dev )

Consider string document output when a client or transport expects query strings and you want to avoid embedding GraphQL AST objects. The client preset supports a string-oriented document mode; select it based on your runtime and client requirements rather than assuming it is universally smaller or better. (the-guild.dev )

Fragments, Nullability, and Custom Scalars

Fragments are useful for sharing selections across operations and components. The client preset can generate fragment masking helpers: a component can declare that it needs a particular fragment, while callers provide data that includes that fragment. This can make data dependencies more explicit, but teams should learn the generated helper conventions and decide whether masking suits their architecture. (the-guild.dev )

Pay particular attention to nullability. GraphQL’s T and T! express different guarantees, and generated TypeScript types reflect those schema distinctions. A nullable field should be handled as potentially null; a non-null schema field is not necessarily present in a response if it was not selected. Conditional directives and partial-data behavior can add further nuance, so inspect generated types rather than guessing at the shape.

Custom scalars need deliberate mappings. A scalar such as DateTime may arrive as a string over JSON even if application code later wraps it in a date type. Configure mappings to match actual runtime representations, and use runtime parsing when conversion or validation is required. GraphQL Code Generator v6 changed the default custom-scalar type to unknown rather than any, helping avoid silently treating unvalidated values as safe. (the-guild.dev )

CI and Team Workflow

Type safety stays trustworthy only when generated artifacts match the schema and operations in the repository. A reliable workflow should:

  • Keep schema inputs versioned or fetch them from a controlled, authenticated source.
  • Run code generation after schema or operation changes.
  • Run generation and TypeScript checks in CI, failing if generated output is stale or operations no longer validate.
  • Exclude generated output from operation discovery, and avoid manually editing generated files.
  • Coordinate generator package upgrades, especially when using multiple official Code Generator packages. The v6 migration guide specifically advises updating related official packages together to avoid compatibility surprises. (the-guild.dev )

For teams generating a schema from a live endpoint, treat credentials and environment selection carefully: development, staging, and production schemas can differ. A reproducible CI build should use an intentional schema source rather than whichever endpoint happens to be available locally.

Common Pitfalls

Generating only schema-wide types. These describe possible API objects, not necessarily the subset returned by a particular operation. Prefer operation result types for UI and application logic.

Using any to silence mismatches. It removes the compiler feedback that code generation was intended to provide. Review scalar mappings and nullability rather than broadly weakening types.

Assuming type safety means runtime safety. Static types do not inspect real server responses or enforce authorization. Treat them as a contract check during development, not a substitute for API tests or runtime validation where needed.

Letting schema and client versions drift. An old schema snapshot can generate perfectly consistent types for an API that has since changed. Keep the schema source and CI checks aligned with the API version your application targets.

Over-customizing too early. Start with a minimal preset configuration, then add custom scalar mappings, fragment behavior, persisted documents, or build optimizations when the project has a concrete need. The preset supports options such as persisted-document generation and string documents, but those features require compatible server or client behavior. (the-guild.dev )

Conclusion

GraphQL type-safe client generation connects the schema, the operation a feature requests, and the TypeScript code that consumes its response. A small setup based on operation documents and generated typed documents can catch mismatched variables and response-field mistakes while reducing handwritten type duplication. The best results come from treating the schema as a versioned contract, regenerating and checking artifacts in CI, and remembering that compile-time guarantees do not replace runtime validation or API testing.

Related Posts