Chen Yang

Make GraphQL Codegen Work with Hasura in Next.js

As I used the GraphQL Code Generator before, I found out that making this Codegen work with Hasura in Next.js needs some special configurations.

Set Codegen Configurations for Hasura

The Hasura's official tutorial provides a settings code block which I modified some "special configurations" in it (with the ⛑️ indicator):

// ./codegen.js

// ⛑️ Change 1: import "dotenv"
require('dotenv').config();

// ⛑️ Change 2: Get Hasura's GraphQL API from environment variables
const API = process.env.HASURA_GRAPHQL_API;

module.exports = {
  schema: [
    {
      // ⛑️ Change 3: Use the `API` variable that just defined
      [API]: {
        headers: {
          // ⛑️ Change 4: Add content type
          'content-type': 'application/json',
          // ⛑️ Change 5: Add admin secret from environment variables
          'x-hasura-admin-secret': process.env.HASURA_ADMIN_SECRET,
        },
      },
    },
  ],
  documents: ['./src/**/*.tsx', './src/**/*.ts'],
  overwrite: true,
  generates: {
    './src/generated/graphql.tsx': {
      plugins: [
        'typescript',
        'typescript-operations',
        'typescript-react-apollo',
      ],
      config: {
        skipTypename: false,
        withHooks: true,
        withHOC: false,
        withComponent: false,
      },
    },
    './graphql.schema.json': {
      plugins: ['introspection'],
    },
  },
};

Explain about these changes:

  • Change 1: for this codegen.js file can get environment variables, we need to install dotenv and import it into this file.
  • Change 2 & Change 3: these two are optional. I don't want to expose my Hasura GraphQL API, so I choose to store it as an environment variable. Whether add these is up to you.
  • Change 4 & Change 5: interacting with Hasura GraphQL API needs some permissions which are specified in the request headers.
Headers in the GraphQL API from Hasura console
Headers in the GraphQL API from Hasura console

In the picture above, at default Hasura GraphQL API needs content-type and x-hasura-admin-secret. This is why I make the "4" and "5" changes. After setting the permissions in the database tables, we can interact with the API with x-hasura-role and x-hasura-user-id. More "permission" content could find in their official tutorials.

Special Attentions for Next.js

We usually put environment variables in the .env.local file for Next.js applications, but this codegen.js file CANNOT read .env.local, so we need to create a .env file in the root directory just for Codegen and put those essential variables in it. The Codegen will not work without this.

Last Step

Don't forget to add a script in the package.json file for using Codgen:

{
  "scripts": {
    "gen": "graphql-codegen --config codegen.js"
  }
}

More Infos

This is a note from me about developing an application with Next.js and Hasura. The app is called DDD App, and it is a tool for remembering German nouns. You can learn more about it here.