Skip to content
Santekno.com | Tech Tutorials and Trends
EN
📖 0%
05 Oct 2025 · 5 min read ·Article 97 / 125
Go

97 GraphQL Code Generator and Schema Automation

IH
Ihsan Arif
Writer at Santekno · Backend Engineer

97 GraphQL Code Generator and Schema Automation: Accelerating Modern API Development

GraphQL is increasingly becoming the de facto standard in modern API development. It offers more flexible querying than REST and enables front-end and back-end teams to collaborate more effectively. However, the maintainability and scalability of a GraphQL schema can pose their own challenges, especially as the number of types, queries, mutations, and resolvers continues to grow.

In this article, I want to discuss one of the most valuable tools for supporting a GraphQL development workflow, namely GraphQL Code Generator . We will also look at how a code generator can help with automation, reduce boilerplate, improve type safety, and speed up time-to-market through real-world examples and process flow diagrams.

Danger
Disclaimer: The title “97 GraphQL Code Generator” here refers to the version and variation of the tool—it does not mean there are 97 different tools. The main focus of this discussion is the GraphQL Code Generator tool, which is extremely popular in the GraphQL ecosystem.

The Challenges of GraphQL Schema Development

When we build a GraphQL API for a real-world service, the process often looks something like this:

MERMAID
flowchart TD
    A[Tulis skema GraphQL] --> B[Tulis resolver (manual)]
    B --> C[Test query]
    C --> D[Perbaiki skema & resolver jika perlu]

Every schema change often requires engineers to update resolvers, TypeScript typings, or generate documentation manually. This is prone to inconsistencies. For example, when there is a change to the schema (type User { ... }), an engineer might forget to update the resolver and the related types, causing a runtime error.


The Solution: Automation with GraphQL Code Generator

GraphQL Code Generator (@graphql-codegen/cli) is here to solve this problem.

What Is GraphQL Code Generator?

Simply put, GraphQL Code Generator is an open-source tool that can generate static code based on the GraphQL schema and the operations (queries/mutations) we create. The output can take the form of TypeScript typings, resolver skeletons, React hooks, and even API documentation.

Key benefits:

  • Type Safety: No more mistyping properties when accessing a response.
  • Reduced Boilerplate: Much of the code is generated automatically, with less manual copy-paste.
  • Consistency: The schema, client code, and resolvers always stay in sync.
  • Productivity: The time it takes to develop new features becomes much shorter.

Case Study: Generating TypeScript Types & React Hooks

Let’s try simulating a simple project.

The GraphQL Schema

Suppose we have the following schema (for example, in a file named schema.graphql):

graphql
 1type User {
 2  id: ID!
 3  name: String!
 4  email: String!
 5}
 6
 7type Query {
 8  users: [User!]!
 9  user(id: ID!): User
10}

A GraphQL Query for the Frontend (src/queries/getUsers.graphql)

graphql
1query GetUsers {
2  users {
3    id
4    name
5    email
6  }
7}

Installing GraphQL Code Generator

Install the dependencies in a Node.js-based project:

bash
1npm install @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations @graphql-codegen/typescript-react-apollo --save-dev

Or via Yarn:

bash
1yarn add @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations @graphql-codegen/typescript-react-apollo --dev

Configuration: codegen.yml

Create a config file named codegen.yml:

yaml
1schema: ./schema.graphql
2documents: ./src/queries/**/*.graphql
3generates:
4  ./src/generated/graphql.tsx:
5    plugins:
6      - typescript
7      - typescript-operations
8      - typescript-react-apollo

The Autogen Process: Workflow Diagram

MERMAID
sequenceDiagram
    autonumber
    User->>CodeGenCLI: run `graphql-codegen`
    CodeGenCLI->>Schema: Baca file schema.graphql
    CodeGenCLI->>Documents: Baca file query .graphql
    CodeGenCLI->>TypeScriptPlugin: Generate typings dari schema
    CodeGenCLI->>ReactApolloPlugin: Generate custom React hooks
    CodeGenCLI->>User: Output file src/generated/graphql.tsx

Running the Generator

bash
1npx graphql-codegen

Once it runs, we get an auto-generated output file, for example src/generated/graphql.tsx.


Examples of the Generated Output

Automatic Typings

typescript
 1export type User = {
 2  __typename?: 'User';
 3  id: string;
 4  name: string;
 5  email: string;
 6};
 7
 8export type GetUsersQuery = {
 9  users: Array<User>;
10};

Automatic React Hook

typescript
1export function useGetUsersQuery(baseOptions?: Apollo.QueryHookOptions<GetUsersQuery>) {
2  return Apollo.useQuery<GetUsersQuery, GetUsersQueryVariables>(GetUsersDocument, baseOptions);
3}
Danger
The effect: Frontend developers can now simply use useGetUsersQuery() and get full autocomplete and type safety. There is no longer any need to manually write the response types, which is error-prone.

Value Comparison Table

FeatureManualWith Codegen
Generate typingsMust be written by handAutomatic from the schema
Schema synchronizationProne to typos, not automaticAlways consistent
Create custom hooksManual, repetitiveAutomatically available per query
MaintainabilityComplex, high riskSimple, predictable
Scaling to large queriesError-prone, not reusableVery easy to reorganize

Schema Automation for the Server (Backend)

Beyond the client side, GraphQL Code Generator can help backend engineers generate skeleton code for resolvers, for example with the typescript-resolvers plugin:

yaml
1  ./src/generated/resolvers-types.ts:
2    plugins:
3      - typescript
4      - typescript-resolvers

The output: Every change in the schema automatically updates the interface in TypeScript. For example:

typescript
1export interface QueryResolvers<ContextType = any> {
2  users: Resolver<Array<User>, {}, ContextType>;
3  user: Resolver<User, { id: string }, ContextType>;
4}

Errors caused by a mismatched return type from a resolver can be drastically reduced! Resolvers also get auto-typed, reducing runtime bugs.


Schema Automation in a Real-World Project

Most engineering teams at unicorns/startups now use pipelines like the following:

MERMAID
flowchart TD
    Dev[Update schema.graphql] --> CI[CI/CD Pipeline]
    CI -->|auto-run| Codegen[GraphQL Codegen]
    Codegen --> Commit[Update commit typings]
    Commit --> Deploy[Deploy]

With this pattern, the schema and the entire code base stay up to date automatically, without disrupting the development flow.


Conclusion

GraphQL Code Generator is one of the essential tools for engineers building modern APIs. It brings automation to the generation of types, hooks, resolver skeletons, and even documentation, so that we can:

  • Increase development speed
  • Reduce human error
  • Guarantee consistency between client and server

Don’t be afraid to give it a try! In large teams, schema automation not only improves code quality but also helps build a healthy engineering culture.


Are you already using codegen in your GraphQL projects? Share your experiences or the challenges you’ve run into in the comments!

Related Articles

💬 Comments