Leo's dev blog

Shopify Hydrogen Codegen Configs

Published on
Published on
/2 mins read/---

Codegen is a tool that generates types for your GraphQL queries. It's automatically generated Typescript types on development based on your GraphQL schemas.

Let's see how to setup a simple Codegen config for a Shopify Hydrogen project.

First, install the @graphql-codegen/cli and @shopify/hydrogen-codegen as dev dependencies with:

npm install @graphql-codegen/cli @shopify/hydrogen-codegen --save-dev

Then create a codegen.ts file in the root of your project with the following content:

codegen.ts
import type { CodegenConfig } from "@graphql-codegen/cli";
import { pluckConfig, preset, getSchema } from "@shopify/hydrogen-codegen";
 
export default {
  overwrite: true,
  pluckConfig,
  generates: {
    "storefront-api.generated.d.ts": {
      preset,
      schema: getSchema("storefront"),
      documents: [
        "./*.{ts,tsx}",
        "./app/**/*.{ts,tsx}",
      ],
    }
  },
} as CodegenConfig;

This is the most basic config for Codegen to generate types for your GraphQL queries. It's read the matching files in the documents, in this case, they are all files in the root and under the app directory that are .ts or .tsx.

The generated types are saved in the storefront-api.generated.d.ts file (you can change the name to whatever you want).

Now, update your package.json to add the codegen scripts:

package.json
"scripts": {
  "codegen": "shopify hydrogen codegen",
  "dev": "shopify hydrogen dev --codegen",
  "build": "shopify hydrogen build --codegen",
}

The @shopify/cli and @shopify/hydrogen is needed also, but I assume you already have them installed cause this is a Hydrogen project.

Now you can run the codegen script to generate the types:

npm run codegen

The codegen will also automatically update the types when you run the dev or build scripts.

Config for the new Customer Account API

If you are using the new Customer Account API, you will need to add a new config for the customer-account schema.

codegen.ts
import type { CodegenConfig } from "@graphql-codegen/cli";
import { pluckConfig, preset, getSchema } from "@shopify/hydrogen-codegen";
 
export default {
  overwrite: true,
  pluckConfig,
  generates: {
    "storefront-api.generated.d.ts": {
      preset,
      schema: getSchema("storefront"),
      documents: [
        "./*.{ts,tsx}",
        "./app/**/*.{ts,tsx}",
        "!./app/routes/*.account*.{ts,tsx}", // Ignore account routes
      ],
    },
    "customer-account-api.generated.d.ts": {
      preset,
      schema: [getSchema("customer-account")],
      documents: ["./app/routes/*.account*.{ts,tsx}"],
    },
  },
} as CodegenConfig;

The config will check all queries in all account routes (files that match the *.account*.{ts,tsx} pattern) and generate types for them in the customer-account-api.generated.d.ts file.

Remember to ignore the account routes in the storefront-api.generated.d.ts file also.

Happy coding!