How to Use Environment Variables in Netlify Functions
When building things using Netlify Functions, there are times you need to access environment variables in your functions. These variables are available at runtime through process.env
when using TypeScript or JavaScript:
process.env.VARIABLE_NAME
A cleaner way to access them is to destructure like this:
const { VARIABLE_ONE, VARIABLE_TWO } = process.env
Define these at the root level, and they'll be accessible throughout your function code.
Managing Variables
There are two main ways to manage environment variables in Netlify:
-
In your repository – Store them in a
.env
file and use a library likedotenv
to load them. However the next way is better as it allows you keep secrets separate from your code. -
Through Netlify's UI – The better way is to set them in Netlify's dashboard under Site settings → Environment variables. This keeps them secure and available during builds and runtime.
What you can't do is to use the variables defined in your netlify.toml file.
Local Development
If you need access to environment variables while developing locally, create a .env
file at the root of your project:
# .env file
API_KEY=your-api-key
Then access them in your function:
const { API_KEY } = process.env
Run netlify dev
to load them automatically.