Content Insights Tip #70 | Type-safe GraphQL with Codegen

Codegen


Having been a developer for a long time, with a background in Java and C#, I've always valued type safety and, even more, the convenience of IntelliSense. The lack of type safety in frontend projects was initially frustrating for me—how does anyone write reliable code without it? 😄 Now, as we transition into a headless CMS world, using TypeScript in our frontend projects is a natural choice. It allows us to write more robust, readable, and predictable code.

Naturally, we want type safety across our entire codebase, including the input and response types for our GraphQL server interactions. Fortunately, there’s a powerful tool for this: GraphQL Code Generator. This NPM package offers a range of features that bring type safety to our GraphQL operations, including:

  • Typed queries, mutations, and subscriptions for frameworks like React, Vue, Angular, Next.js, Svelte, and more—whether you're using Apollo Client, URQL, or React Query.
  • Typed GraphQL resolvers for Node.js (GraphQL Yoga, GraphQL Modules, TypeGraphQL, or Apollo) or Java GraphQL servers.
  • Fully-typed SDKs for Node.js, Apollo Android support, and additional integrations.
With GraphQL Code Generator, you can generate types by running a single command:
npm run codegen

This command connects to the GraphQL server, performs schema introspection, and validates your queries and mutations. It then generates type-safe inputs and responses based on them, making your code more reliable.

Setting Up GraphQL Code Generator

To get started, install the required packages by running these commands in your terminal:
  • npm install graphql
  • npm install --save-dev typescript @graphql-codegen/cli
After installation, configure a codegen.ts file. This configuration file specifies where GraphQL Code Generator should find the schema, handle authentication, locate query and mutation documents, and store generated files. For complete details, refer to the official documentation.

Note: Avoid installing graphql, @graphql-codegen/cli, and related plugins globally. Doing so can cause issues due to duplicated GraphQL package dependencies. Install them locally in your project instead.

Important Next.js Note

To avoid a common Next.js limitation, make sure to directly import GraphQL like this:
  • import { graphql } from '../types/gql/gql';
If you attempt to re-export all exports from a page, Next.js will throw an error: “Re-exporting all exports from a page is disallowed.”

With that set-up, you can enjoy a type-safe GraphQL experience in your frontend projects. Happy coding!