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. -
Enable fetching of GraphQL introspection data by adding the following example script to the
/scripts/fetch-graphql-introspection-data.tsfile: -
Configure
graphql-codegenby creating agraphql-codegen.ymlat the root of your app containing the following: -
Run the following command to generate the
src/temp/graphql-types.tsfile containing the necessary types.