What is an environment variable?
An environment variable is a setting stored outside the code, like a web address or a secret key, so the same code can run in different places safely.
Last updated
In real life
Like a hotel key card: the lock on the door, the code, stays the same, but each guest gets their own card, the setting.
Try it yourself
The demo runs the same code in two places. On your laptop, the environment variables point to localhost and a test key, so emails go to a test inbox. On the live site, they hold the real address and a secret key, and the code doesn't change.
The code (the same everywhere)
const site = process.env.SITE_URL;
const key = process.env.EMAIL_API_KEY;
sendOrderEmail({ key, link: site + "/orders" });The code only names the settings. It never contains the key itself.
Environment variables: your laptop (testing)
- SITE_URL
- http://localhost:3000
- EMAIL_API_KEY
- test_key_123
Order emails go to a test inbox. No real customer is emailed.
Environment variables are settings that live outside the code. Switch places: the code doesn't change, but the web address and the key do.
Environment variable vs API key
An API key is one kind of secret. An environment variable is where you keep it, along with other settings, so the key never sits in your code.
Common questions
What is a .env file?
A file of environment variables for your own computer, one per line, like SITE_URL=http://localhost:3000. It should never be committed or shared.
Where do environment variables go on a live site?
In the hosting company's settings, usually on a page called environment variables. The host passes them to your code when it runs.
Where you will use this
Quick check: Environment variable
Question 1 of 3