Implement GraphQL code generation

Version: 22.x

GraphQL code generation provides a lot of benefits, including type safety, faster development, improved developer experience, and so on. Originally, GraphQL code generation was included out of the box in JSS Next.js applications. However, as of JSS version 22.7.0 this was removed from the Next.js starter application, leaving the decision of whether to use GraphQL code generation to individual developers.

The reasons for this removal were two-fold:

  • If your application does not require automatic GraphQL code generation, removing this functionality reduces the complexity of the app.

  • The old method relied on the graphql-let package, which is no longer maintained and therefore has the potential to introduce security vulnerabilities to your app.

If you want to manually implement a similar capability in your app, the following example demonstrates how to do this using graphql-codegen.

To implement GraphQL code generation using graphql-codegen:

  1. Add the following dev dependencies to your app's package.json file if not already present, then install them with the npm install command.

    RequestResponse
    "graphql": "^16.11.0",
    "graphql-tag": "^2.12.6",
    "@graphql-codegen/cli": "^5.0.7",
    "@graphql-codegen/typescript": "^4.1.6",
    "@graphql-codegen/typescript-operations": "^4.6.1",
    "@graphql-codegen/typescript-react-query": "^6.1.1",
    
  2. Enable fetching of GraphQL introspection data by adding the following example script to the /scripts/fetch-graphql-introspection-data.ts file:

    RequestResponse
    import { GraphQLRequestClient } from "@sitecore-jss/sitecore-jss-nextjs/graphql";
    import fs from "fs";
    import { getIntrospectionQuery } from "graphql";
    
    let jssConfig;
    
    // modify path the runtime config if needed
    jssConfig = require("../src/temp/config");
    
    console.log(
      `Fetch graphql introspection data from ${jssConfig.graphQLEndpoint}...`
    );
    
    const client = new GraphQLRequestClient(jssConfig.graphQLEndpoint, {
      apiKey: jssConfig.sitecoreApiKey,
    });
    
    client
      .request(getIntrospectionQuery())
      .then((result) => {
        fs.writeFile(
          "./src/temp/GraphQLIntrospectionResult.json",
          JSON.stringify(result, null, 2)
        );
      })
      .catch((e) => {
        console.error(e);
      });
    
  3. Configure graphql-codegen by creating a graphql-codegen.yml at the root of your app containing the following:

    RequestResponse
    overwrite: true # Overwrite existing files
    documents: 'src/**/*.graphql' # Adjust the path to your GraphQL documents
    schema: 'src/temp/GraphQLIntrospectionResult.json' # the path to your introspection result file
    generates:
      src/temp/graphql-types.ts: # The output file for generated types
        plugins:
          - 'typescript' # Generates TypeScript types for GraphQL operations
          - 'typescript-operations' # Generates TypeScript types for GraphQL operations
          - 'typescript-react-query' # Generates React Query hooks for GraphQL operations
    
  4. Run the following command to generate the src/temp/graphql-types.ts file containing the necessary types.

    RequestResponse
    graphql-codegen --config graphql-codegen.yml

Do you have some feedback for us?

If you have suggestions for improving this article,