Speakeasy Logo
Skip to Content

Authenticating with local environment variables

When authenticating with an API using a SDK, its a common pattern for the value of an API_KEY or token to default to the value of an environment variable. This allows you to easily switch between different environments without changing the code.

In this example, we’ll show you how to use a SDK Hook enable your users to authenticate with your API using local environment variables. A SDK Hook is a function that will be executed by the SDK at a specific point in the request lifecycle. For this use case we’ll leverage a BeforeRequest hook.

Inside of our Speakeasy generated SDK hooks are written in the src/hooks/ directory. We’ll make a new hook called in a file called auth.ts.

This hook will check for the presence of an environment variable named API_KEY and if it exists, it will add it to the Authorization header of the request.

Finally to ensure the SDK uses this hook, we need to add it to make sure it is registered with the SDK. This is done in the src/hooks/registration.ts file.

Finally make sure to update the usage snippet in your readme to reference the environment variable.

Last updated on