Skip to main content

How to use environment variables in Netlify functions

Learn how to correctly manage and access environment variables in Netlify Functions.

1 min read
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:

TypeScript
process.env.VARIABLE_NAME

A cleaner way to access them is to destructure like this:

TypeScript
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:

  1. In your repository – Store them in a .env file and use a library like dotenv to load them. However the next way is better as it allows you keep secrets separate from your code.

  2. 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:

Terminal
# .env file
API_KEY=your-api-key

Then access them in your function:

TypeScript
const { API_KEY } = process.env

Run netlify dev to load them automatically.


Comments

No comments yet. Be the first to share your thoughts.

Leave a comment

Comments are moderated before they appear.

People found this searching for

  • netlify environment variables
  • site:perttu.dev