Generate Persisted Documents with GraphQL Code Generator

Automatically persist GraphQL operations to JSON with the client preset plugin.

The GraphQL Code Generator client-preset is a great way to generate a TypedDocumentNode for all GraphQL operations of your application.

You can also use the client-preset to automatically persist documents to JSON for use with your GraphQL server to only allow the operations used by your application.

This prevents unwanted operations from being executed by your server.

Install and setup GraphQL Code Generator

To begin you will want to install the GraphQL Code Generator dependencies:

npm install --save-dev typescript @graphql-codegen/cli @graphql-codegen/client-preset

Finally don't forget to install graphql itself as a dependency:

npm install graphql

Configure the client-preset

Inside the root of your project create the file codegen.ts:

touch codegen.ts

Then add the following configuration but make sure to update the path to your schema (which can be a URL), the documents glob and pass persistedDocuments: true to the generator:

import { CodegenConfig } from "@graphql-codegen/cli";

const config: CodegenConfig = {
  documents: ["app/**/*.{ts,tsx}"],
  ignoreNoDocuments: true,
  generates: {
    "./gql/": {
      preset: "client",
      plugins: [],
      presetConfig: {
        persistedDocuments: true,

export default config;

You can learn more about all of the configuration above and what it means in Episode 67.

Jamie Barton

Published on 6 Feb 2023 by Jamie Barton