One line, const API_KEY = "sk-abc123xyz";, looks harmless. But code gets copied everywhere: to git, to your teammates' laptops, to the CI server (the server that tests and builds your code automatically), and part of it even to every visitor's browser. Anyone who reads that key can use your account, and the bill comes to you.
A value like that API key is called a secret: a value that opens access, such as an API key, a database password, or a key that signs tokens. Its place is not in the code. Think of your ATM card's PIN: you don't write it on the card, because the card goes everywhere with you and can be photocopied. The card is the code, and the PIN is the secret. So a secret is kept apart, in an environment variable (a variable the system gives the program when it runs), and the code only names it.
Code reads a name, the value comes from outside
These are two ways to write the same key, a bad one and a good one:
// BAD: the secret is written in the code and committed to git
const API_KEY = "sk-abc123xyz";
// GOOD: the code only knows the name, the value is supplied when the program runs
const API_KEY = process.env.OPENAI_API_KEY;
process.envis a Node.js object holding every environment variable.process.env.OPENAI_API_KEYreads one value by its name, and givesundefinedwhen that variable isn't set.- Once the BAD line is in a commit, that secret sits in the git history (the record of every change to the code) of every clone (copy) of the repo. Deleting it in the next commit is not enough.
While you develop on your laptop, the values go in a .env file in the project's main folder:
# .env (only on your laptop, never committed)
STRIPE_SECRET_KEY=sk_live_abc123
OPENAI_API_KEY=sk-abc123xyz
Node 20.6 and later can read that file directly with node --env-file=.env server.js. Older versions use the dotenv package. On the production server, the values are set through the hosting settings or a secret manager (a service made for storing secrets), not through a file shipped with the code.
.gitignore and .env.example
You make these two files together with .env:
# .gitignore
node_modules
dist
.env
# .env.example (committed: a list of names, no values)
STRIPE_SECRET_KEY=
OPENAI_API_KEY=
.envin.gitignoremeans git never offers that file for a commit..env.exampletells your teammates which variables they have to fill in, without leaking the values.
If .env has already been committed, .gitignore doesn't help: a file git already tracks stays tracked. Take it out of tracking with git rm --cached .env, commit, then replace (rotate) every key in it, because the old values are still in the history.
The VITE_ and NEXT_PUBLIC_ prefixes mean public
In Vite (a build tool for the frontend), only variables that start with VITE_ can be read by frontend code through import.meta.env. On npm run build (turning the code into files ready to ship), Vite pastes their values as plain text into the JavaScript file every visitor downloads. That built file is called the bundle. Next.js does the same for NEXT_PUBLIC_. This is the project in the Lab, with a Stripe (payment service) secret that has the VITE_ prefix:
// src/checkout.js (runs in the browser)
fetch("https://api.stripe.com/v1/payment_intents", {
method: "POST",
headers: { Authorization: `Bearer ${import.meta.env.VITE_STRIPE_SECRET_KEY}` },
});
After the build, search the dist/ folder (the build output) for that secret with grep (a terminal command that searches text):
$ npm run build
$ grep -rnoE "sk_live_[0-9A-Za-z]+" dist/
dist/assets/index-D7nb3Uqz.js:1:sk_live_abc123
The secret is in the bundle, and anyone can read it in DevTools. So even with .env in .gitignore, that VITE_STRIPE_SECRET_KEY is not safe. .gitignore only keeps the .env file out of git, not out of the build.
The fix: a secret never takes that prefix, and the call that needs it moves to the server. The browser calls your own server, and the server holds the key:
// src/checkout.js (browser): call your own server
fetch(import.meta.env.VITE_API_URL + "/pay", { method: "POST", body: JSON.stringify({ orderId }) });
// server/pay.js (server): the secret stays on the server
fetch("https://api.stripe.com/v1/payment_intents", {
method: "POST",
headers: { Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}` },
});
What may really be public: an API URL (VITE_API_URL), a Stripe publishable key (pk_live_..., a key made for the browser), and a Supabase anon key (Supabase's public key). What may not: anything with secret, private, password or service role in its name.
Laravel: env() in config, config() in code
In Laravel, env('API_KEY') reads an environment variable from .env. The rule: call env() only in the files inside the config/ folder, and let the rest of the code read through config():
// config/services.php
'openai' => ['key' => env('OPENAI_API_KEY')],
// in a controller
$key = config('services.openai.key');
The command php artisan config:cache saves all the config in one cache file, and it usually runs on deploy. After that, .env is no longer read, and env() outside the config/ folder returns null for values that exist only in .env.
Check before you start: validateEnv
A server that starts with an empty variable only fails when that variable is used, say in the middle of a payment. It's better to check as soon as the server starts. This validateEnv function takes a list of the variable names that must exist:
function validateEnv(requiredVars) {
const missing = requiredVars.filter((name) => !process.env[name]);
return { valid: missing.length === 0, missing };
}
process.env.DB_HOST = "localhost";
process.env.DB_PASSWORD = "secret";
console.log("All set:", JSON.stringify(validateEnv(["DB_HOST", "DB_PASSWORD"])));
console.log("Missing API_KEY:", JSON.stringify(validateEnv(["DB_HOST", "DB_PASSWORD", "API_KEY"])));
The result:
All set: {"valid":true,"missing":[]}
Missing API_KEY: {"valid":false,"missing":["API_KEY"]}
filterchecks every name and keeps the ones with no value.!process.env[name]istrueforundefinedand for the empty string"", so a variable set to nothing counts as missing too.validistruewhenmissingis empty.- The two lines that set
DB_HOSTandDB_PASSWORDonly make example values to try the function. In a real app, the values come from.envor the server settings. JSON.stringifyturns the object into JSON text, with quotes around the property names:{"valid":true,"missing":[]}. Without it,console.login Node prints{ valid: true, missing: [] }.
⚠️ What leaks a secret, or leaves it empty
- Thinking
.gitignoreremoves a file that's already committed. Rungit rm --cached .env, then replace (rotate) the keys. - A secret with a
VITE_orNEXT_PUBLIC_prefix. Its value ends up in the browser bundle. Move the call to the server. env()in a Laravel controller. Afterconfig:cache, it returnsnull. Putenv()in aconfig/file, then read it withconfig().- Printing
validateEnv's result withoutJSON.stringify. The output becomes{ valid: true, missing: [] }with no quotes. In the exercise, the JSON form{"valid":true,"missing":[]}is what's asked for.
TL;DR: Code only names a secret (a value that opens access, such as an API key): process.env.OPENAI_API_KEY, or config('services.openai.key') in Laravel. Its value comes from an environment variable, which the system gives the program when it runs. Keep local values in a .env that's in .gitignore (the list of files git ignores), and commit a .env.example with no values. If .env was ever committed, run git rm --cached .env, then replace (rotate) every key in it. The VITE_ and NEXT_PUBLIC_ prefixes mean the value is pasted into the bundle (the JavaScript file the browser downloads), so a secret goes without a prefix and is used on the server. When the server starts, check the required variables with filter and !process.env[name], then print the result with JSON.stringify.
⚡ The code only knows the name
Write:
const API_KEY = process.env.OPENAI_API_KEY;
Guess first: const API_KEY = "sk-abc123xyz"; and the file is committed. What's the danger?
The key is hardcoded (written directly in the code) and ends up in git. It sits in the git history (the record of every change to the code) of every clone (copy) of the repo, and deleting it in the next commit is not enough.
Meaning: A secret (a value that opens access, such as an API key) is not written in the code. The code only names it. The value comes from an environment variable, a variable the system gives the program when it runs. process.env is a Node.js object holding the environment variables, and it gives undefined when the variable isn't set.
⚡ .env in .gitignore, .env.example committed
Write:
# .env.example (committed: a list of names, no values)
STRIPE_SECRET_KEY=
OPENAI_API_KEY=
Meaning: The secret values on your laptop are kept in a .env file, and .env is written in .gitignore, so git never offers it for a commit. What you commit is .env.example: a list of variable names with no values. If .env has already been committed, take it out of git's tracking and replace (rotate) every secret in it.
⚡ The VITE_ prefix means public
Meaning: On build (turning the code into files ready to ship), Vite (a build tool for the frontend) pastes the values of variables whose names start with VITE_ into the JavaScript file every visitor downloads. So a secret never takes that prefix. Move the call that needs the secret to the server, and let the server hold the key.