How to use environment variables in Netlify functions
By Flavio Copes
Learn how to read environment variables in Netlify Functions through process.env, where to set them in the dashboard, and how Edge Functions use Deno.env.get.
To use environment variables in your Netlify Functions, read them from process.env, like in any Node.js program:
process.env.STRIPE_SECRET_KEY
Environment variables are how you keep secrets out of your code. API keys, database URLs, tokens: they all live in the environment, and the function reads them at runtime.
You can use object destructuring at the beginning of your JS file, to make the code nicer:
const { STRIPE_SECRET_KEY } = process.env
so you can just use STRIPE_SECRET_KEY in the rest of the program.
Here’s a full function that uses one:
exports.handler = async () => {
const { API_TOKEN } = process.env
const response = await fetch('https://api.airtable.com/v0/appXyz/Orders', {
headers: { Authorization: `Bearer ${API_TOKEN}` }
})
return {
statusCode: 200,
body: JSON.stringify(await response.json())
}
}
Where do you set the variables?
You set them through the Netlify administration interface, under your site’s environment variables settings.
You could also declare them in netlify.toml in your repo, but I’d recommend using the Netlify UI. That file is committed to Git, so anything you put there is visible to everyone with repo access. Not what you want for secrets.
One thing that catches people: values in process.env are always strings. If you store MAX_ITEMS=50, comparing it to a number needs a conversion first, with parseInt() or Number().
Why is my variable undefined?
The most common cause: you added or changed the variable in the UI, but the running functions still have the old environment. Variables are applied when the site deploys, so trigger a new deploy after changing them.
When testing locally, run your site with the Netlify CLI (netlify dev). It injects the variables from your site settings, so the function behaves like it does in production.
What about Edge Functions?
Reading process.env does not work on Netlify Edge Functions, just on Netlify “regular” Functions that run on AWS Lambda.
Edge Functions run on Deno, so you need Deno.env.get():
Deno.env.get('API_TOKEN')
Example:
export default () => new Response(Deno.env.get('API_TOKEN'))
Same variables, same settings page. Only the way you read them changes.
Related posts about services: