When using Serverless Functions, it may be necessary to pass environment variables, allowing you to specify potentially different behavior based on the environment it is running in.

Adding environment variables requires two steps, defining the environment variable, then making it available to your Serverless Functions.

Adding Secrets

To define an environment variable for a deployment, use Now Secrets. By using Now Secrets, the data will be encrypted and stored securely.

Adding Now Secrets can be done with Now CLI, which provides three options to work with them.

To define a Now Secret, use the following command:

now secrets add <secret-name> <secret-value>

Defining a Now Secret using Now CLI.

To remove a Now Secret, use the following command:

now secrets rm <secret-name>

Removing a Now Secret using Now CLI.

To rename a Now Secret, use the following command:

now secrets rename <secret-name> <new-name>

Renaming a Now Secret using Now CLI.

Providing Environment Variables

To provide your Serverless Functions with the environment variables you have defined, whether declared in a .env file or as a Now Secret, create a now.json file like the one below:

{
  "env": {
    "VARIABLE_NAME": "@variable-name"
  }
}

An example now.json file that provides Serverless Functions with a defined environment variable.

To use the environment variable from inside the application you would need to reference it using the correct syntax for the language being used. For example, using Node.js, the syntax would be:

process.env.VARIABLE_NAME

Accessing a defined environment variable from within a Node.js application.

Now, whenever the process.env.VARIABLE_NAME key is used, it will provide the application with the value declared either by the Now Secret or environment variable, dependent on the environment the application is running in.

Note: To use environment variables at the build step of your application, refer to the build step documentation.

During Local Development

When using now dev to develop your Serverless Functions locally, Now Secrets are not available. This is a security measure, to prevent accidental use of production secrets during development.

To use environment variables during local development, create a .env file at the root of your project directory, for example:

VARIABLE_NAME=variable_value

An example .env file that provides Serverless Functions with a defined environment variable.

Related

For more information on what to do next, we recommend the following articles: