Environment Variables and Secrets
How environment variables configure your app, where to keep passwords and API keys, and what to do when a secret leaks.
Key takeaways
- Environment variables let the same code run with different settings on your laptop, a test server and the live site.
- A
.envfile is convenient for local development, but it must be listed in.gitignoreand never committed. - Anything shipped to the browser is public, so a secret placed in front-end code is no longer a secret.
- Environment variables are not encrypted, and other processes, logs or error pages can expose them if you are careless.
- A leaked secret has to be revoked and replaced; deleting the line that contained it is not enough.
An environment variable is a named value that the operating system hands to a program when it starts. Web applications use them to receive settings that differ between machines, such as a database address, and secrets such as API keys, without writing those values into the code.
The practical rule is short: code goes in your repository, configuration goes in the environment, and secrets go somewhere with tight access control. The rest of this guide shows how to do that on a laptop and on a server, and what to do when something slips out.
What an environment variable is
Every running process carries a small table of names and values. When one program starts another, the child receives a copy of that table. You have used it already: PATH is the variable that tells your shell where to look for commands.
Names are conventionally written in capitals with underscores, for example DATABASE_URL or SMTP_PASSWORD. Values are always plain text. If your app needs a number or a true/false setting, it has to convert the string itself, and the string "false" counts as true in many languages if you only test whether it is non-empty.
Because the child gets a copy, changing a variable in your terminal doesn't affect a program that is already running. After changing configuration on a server, you normally restart or reload the application.
Set and read variables
The commands depend on your shell. These set a variable for the current terminal session only.
# macOS or Linux (bash, zsh)
export APP_ENV=development
echo "$APP_ENV"
# one command only
APP_ENV=test node app.js # Windows PowerShell
$env:APP_ENV = "development"
echo $env:APP_ENV Reading them in code is just as short. Node.js uses process.env.APP_ENV, Python uses os.environ["APP_ENV"] or os.getenv("APP_ENV"), and PHP offers getenv('APP_ENV').
To make a variable persist, you set it where the program is launched: a shell profile for your own account, a service definition for a background service, the settings panel of your hosting platform, or the configuration of a container. Menu names differ between providers, so look for "environment variables" or "secrets" in your host's documentation.
Use .env files for local work
Typing export lines every morning gets old, so many projects keep a file named .env:
APP_ENV=development
DATABASE_URL=postgres://app:localpassword@localhost:5432/shop
PAYMENT_API_KEY=test-key-placeholder The operating system doesn't read this file by itself. A library, a framework or a tool such as a container runner loads it and puts the values into the environment. Quoting rules vary between loaders, so check yours if a value contains spaces or #.
Add .env to .gitignore before the first commit. Then commit a companion file, often called .env.example, listing the names with harmless placeholder values. New collaborators copy it and fill in their own, and everyone can see which settings the app expects. The guide to Git for web projects covers ignore files in more detail.
Never place a .env file inside the folder your web server publishes. A misconfigured server will hand it to anyone who asks for it by name.
Configuration and secrets are different
Not every setting needs the same care. A page size, a log level or a feature switch is configuration: harmless if read, and fine to keep in a versioned file. A secret is any value that grants access or proves identity.
Typical secrets include:
- database passwords and connection strings that contain them
- API keys and access tokens for outside services
- keys used to sign session cookies or tokens
- private keys for certificates and SSH
- webhook signing secrets
For each secret, ask what someone could do with it. A key that can only read public data is a small problem. A key that can issue refunds or delete your database is a large one. Where a provider allows it, create keys with the narrowest permissions the task needs, and use separate keys for development and production. The overview of API keys, tokens and OAuth explains the differences between credential types.
Keep secrets out of the browser
Front-end code runs on your visitor's device. Every script, every network request and every bundled value can be inspected with the browser's developer tools.
Several front-end build tools let you reference environment variables in client code, usually requiring a special prefix on the name. Those values are copied into the JavaScript at build time. The prefix is effectively a statement that the value is public.
If a feature needs a secret, route it through your own server. The browser calls your endpoint, your server adds the key and calls the outside service, and only the result goes back. Add authentication or rate limits to that endpoint, or strangers can use your key by proxy.
Some keys are designed to be public, such as certain map or analytics identifiers. Providers say so in their documentation, and often let you restrict them to your domain.
Know the limits of environment variables
Environment variables are a delivery method. They offer no encryption of their own.
On a server, an administrator can usually inspect a process's environment. Child processes inherit it, including tools your app runs that have no need for your database password. Crash reporters and debug pages sometimes dump the whole table. A line such as a PHP information page left online can reveal every value.
Reduce the exposure with a few habits. Turn off detailed error pages in production. Don't log the environment or full request headers. Redact tokens in anything you paste into a support ticket or a chatbot. Restrict file permissions on any file holding secrets so only the service account can read it, for example chmod 600 app.env on Linux or macOS.
Check settings when the app starts
A missing variable often surfaces hours later, as a confusing error deep inside a payment or email routine. Read and validate your settings once, at startup, and stop with a clear message if something required is absent.
A good startup check confirms that each required name exists, that numbers and addresses parse, and that obviously wrong combinations are rejected, such as a test payment key on the production environment. The error should name the missing setting without printing any secret values. Gathering this in one configuration module also gives you a single place to see everything the application depends on.
When to use a secret manager
A secret manager is a service that stores secrets encrypted, controls who and what may read them, and records each access. Cloud platforms offer their own, and independent products exist.
For a small site on one host, the host's protected settings panel is often enough. A dedicated manager earns its setup time when several people or servers share secrets, when you need to know who read what, or when you want automatic rotation, meaning a scheduled replacement of keys.
One question remains in every design: how does the application prove to the manager that it is allowed to read? Cloud platforms commonly solve this by giving the running machine its own identity, so no starter password has to be stored. Build pipelines have similar protected variables, but scripts can still print them, so limit who can change the pipeline.
What to do when a secret leaks
Assume a published secret has been copied. Automated scanners watch public code hosts for keys, and exposure can be exploited quickly.
- Revoke or rotate the credential at the provider. This is the step that actually protects you.
- Put the replacement in your environment or secret store and restart the application.
- Check the provider's usage logs and your bill for activity you don't recognize.
- Remove the value from the code, and clean it from history if you wish, knowing that copies and forks may keep it.
- Work out how it got there, then add a guard such as an ignore rule or a secret scanner that runs before commits.
Rewriting history without rotating is the common mistake. It tidies the repository while leaving the old key working for whoever saw it.
Common questions
Why does my app say a variable is undefined?
Check that the process was started after you set it, that the name matches exactly (case matters on Linux and macOS), and that your .env loader runs before the code that reads the value. Services started by the system don't inherit your terminal's exports.
Can I commit an encrypted secrets file?
Some tools support this, and it can work well for small teams. You still have to protect and distribute the decryption key, and anyone who once held it can read old versions.
Should I generate secrets by hand?
No. Use a random generator or your language's cryptographic random function, and make signing keys long. A password generator is fine for many account passwords; follow your framework's instructions for its signing keys.