When using Serverless Functions, it may be necessary to use environment variables.
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>
To remove a Now Secret, use the following command:
now secrets rm <secret-name>
To rename a Now Secret, use the following command:
now secrets rename <secret-name> <new-name>
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" } }
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
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.
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
Reserved Variables
The ZEIT Now platform reserves the usage of some environment variable names by default. You can find a list of these names in the configuration documentation.
Related
For more information on what to do next, we recommend the following articles: