Using graphql-code-generator with authenticated endpoints

Dotan Simha’s graphql-code-generator is a really useful utility to generate integration code from GraphQL APIs for multiple languages.

As outlined in their docs, using the graphql-codegen cli with static config is straightforward:

This post outlines how to use the code-generator CLI when the API is authenticated.

graphql-codegen uses cosmiconfig for loading the configuration. Thanks to cosmiconfig, this configuration can be a dynamic module instead of a static yaml/json file.

So we can have arbitrary logic inside the module. For instance if our graphql API is protected by HTTP basic auth, we can prompt the user for credentials and send them as a header:

So the next time we run graphql-codegen --config ./path/to/config.js we will be prompted for password.

You can, of course, also do things like keep the credentials in an uncommitted file and then read them in the config file.