Compute and AI

Add environment variables

Learn to add environment variables to Functions.

Environment variables allow you to keep secrets, like tokens or API keys, hidden and out of version control. Functions allow you to manage environment variables from the CLI so they are available to your deployed functions.

In this guide, you'll learn to add environment variables and access them from within your function code.

Prerequisites:

  • Complete the Functions quick start, or be comfortable creating and deploying a function.
  • sanity CLI v3.88.1 or higher is required to interact with Blueprints and Functions. You can always run the latest CLI commands with npx sanity@latest.

Create a function

If you don't already have a Blueprint and function set up, create them now.

Initialize a Blueprint:

Add a function:

In this example, we'll set the function to trigger on Document Publish, use TypeScript, and set the name to envExample.

This creates a function in the functions/envExample directory.

Develop locally

Environment variables aren't available locally, but you can simulate them by appending the variable and value to your CLI commands.

Start by updating the function to display the variable. For this example we'll reference a variable called SANITY_SECRET_SAUCE.

All environment variables are accessible on process.env.

To test the function's access to a variable, we'll append it to the CLI command.

If everything worked, you'll see this output:

Now that we know it works locally, let's make it work on Sanity's infrastructure.

Add an environment variable

Before you can add environment variables, you need to deploy the blueprint.

With the blueprint deployed, you can add environment variables to the function.

Add them with the functions add env <function-name> <variable-name> <variable-value> command.

Now make changes to your documents, and check the logs for the function. You should see a similar log to the one from the local test.

You've now deployed and accessed an environment variable from a function.

As with other examples, if you're done with this function and blueprint, it's a good practice to destroy it to prevent unexpected billing.

Additional env commands

As we saw with the command earlier, environment variables are linked to individual functions. In addition to add, you can use the following commands to interact with them:

  • sanity functions env list <function-name>: List all environment variables for the given function.
  • sanity functions env remove <function-name> <variable-name>: removes the variable from the deployed function.

For additional usage information, add --help after each CLI command. You can read more about the CLI in the Functions CLI reference.

Was this page helpful?