Gaurab Paul

Polyglot software developer & consultant passionate about web development, distributed systems and open source technologies

Support my blog and open-source work

Tags

Using graphql-code-generator with authenticated endpoints
Posted  4 years ago

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.