Implement GraphQL code generation
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-letpackage, 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:
-
Add the following dev dependencies to your app's
package.jsonfile if not already present, then install them with thenpm installcommand.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", -
Enable fetching of GraphQL introspection data by adding the following example script to the
/scripts/fetch-graphql-introspection-data.tsfile:RequestResponseimport { 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); }); -
Configure
graphql-codegenby creating agraphql-codegen.ymlat the root of your app containing the following:RequestResponseoverwrite: 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 -
Run the following command to generate the
src/temp/graphql-types.tsfile containing the necessary types.RequestResponsegraphql-codegen --config graphql-codegen.yml