Open almost any modern project, whether it's Laravel, Node.js, Django, or a React app, and you'll find a small file called .env sitting in the root, or at least a .env.example showing what it should contain. Inside are lines like DB_PASSWORD=... and API_KEY=.... That file is one of the most important, and most frequently mishandled, files in web development.
This guide explains environment variables and .env files: what they are, why developers use them, how to set them on shared hosting and VPS servers, and how to make sure your secrets never end up somewhere public.
What is an environment variable?
An environment variable is a named value that lives in the environment a program runs in, rather than in the program's code. Every process on a computer has a set of them. You've likely seen some already:
PATHtells the system where to find programs.HOMEpoints to your home directory.
You can see them in a terminal:
echo $HOME # macOS and Linux
printenv # list all of them
Applications can read environment variables too. In Node.js it's process.env.DB_HOST. In Python it's os.environ["DB_HOST"]. In PHP it's getenv('DB_HOST') or $_ENV['DB_HOST'], depending on configuration.
Why not just put settings in the code?
Because code and configuration have different jobs.
- Security. Code gets shared: pushed to GitHub, sent to freelancers, copied between servers. Passwords and API keys written into the code travel everywhere the code goes.
- Different environments. Your laptop, a staging site, and the live site all run the same code but need different databases, API keys, and debug settings. Environment variables let one codebase behave correctly in each place.
- Easy changes. Rotating a leaked key means changing one value on the server, not editing and redeploying code.
This approach is a core idea of the widely cited "Twelve-Factor App" methodology, which recommends storing configuration in the environment.
What is a .env file?
Setting dozens of variables by hand in every terminal session would be tedious. A .env file is a simple text file that lists them:
APP_ENV=production
APP_DEBUG=false
DB_HOST=localhost
DB_DATABASE=myapp
DB_USERNAME=myapp_user
DB_PASSWORD=change-me-to-something-long
MAIL_FROM=hello@example.com
A library loads the file when the app starts and puts those values into the environment. Examples include dotenv for Node.js, python-dotenv for Python, and vlucas/phpdotenv, which Laravel uses. Newer versions of Node.js can also load a file directly with the --env-file flag.
Format basics
- One
KEY=valueper line, with no spaces around the=to be safe. - Quote values that contain spaces or special characters:
APP_NAME="My Shop". - Lines starting with
#are comments. - Exact rules vary slightly between libraries, so check yours if something odd happens with quotes or
#characters inside values.
The golden rule: never commit .env
Your .env file should never go into Git. Add it to .gitignore:
.env
.env.local
.env.*.local
Instead, commit a .env.example with all the keys but placeholder values:
DB_HOST=localhost
DB_DATABASE=
DB_USERNAME=
DB_PASSWORD=
MAIL_API_KEY=
New developers copy it to .env and fill in their own values. Everyone knows what's needed, and no real secrets live in the repository.
If you already committed secrets
Deleting the file in a new commit isn't enough, because the secret is still in the Git history. The safe response:
- Rotate the secrets immediately. Change the database password, regenerate API keys. Assume they're compromised.
- Remove the file from tracking:
git rm --cached .env, then commit. - If the repository is public or widely shared, consider rewriting history with a tool like
git filter-repo, but rotation comes first.
Keep .env out of public view on the server
On a web server, a .env file inside your public folder could be downloaded by anyone who requests https://example.com/.env. Bots scan for exactly this. Protect it:
- Best: keep
.envabove the web root. Frameworks like Laravel are designed this way: only thepublicfolder is web-accessible, and.envsits one level up. - On Apache or LiteSpeed, block dotfiles in
.htaccess:
<FilesMatch "^\.">
Require all denied
</FilesMatch>
- On Nginx, deny hidden files while allowing
.well-knownfor SSL validation:
location ~ /\.(?!well-known) {
deny all;
}
Test by visiting https://yourdomain.com/.env in a browser. You should get a 403 or 404, never the file contents.
Also set tight file permissions so other users on the server can't read it, for example chmod 600 .env where your setup allows.
Setting environment variables in different places
Shared hosting with cPanel or DirectAdmin
For PHP apps, a .env file above public_html is the usual approach. If your panel offers an application manager for Node.js or Python apps, it typically includes a section to add environment variables directly, which the panel passes to your app when it starts.
A VPS with systemd
Point your service at an environment file:
[Service]
EnvironmentFile=/srv/myapp/.env
Or set individual values with Environment=KEY=value lines. Reload with sudo systemctl daemon-reload and restart the service.
PM2 (Node.js)
Define variables in the env section of ecosystem.config.js, or have your app load .env with dotenv.
Docker
Use env_file: .env or an environment: section in compose.yaml. Docker Compose also reads a .env file in the project folder to fill in ${VARIABLES} in the compose file itself.
Hosting platforms and CI
Deployment platforms and CI services have a settings page for environment variables or secrets. Use it rather than committing files, and mark sensitive values as secret so they're hidden in logs.
Front-end apps are different
Build tools like Vite and Create React App read .env files too, but they embed the values into the JavaScript sent to the browser. In Vite, only variables starting with VITE_ are exposed, specifically to prevent accidents. Anything you expose this way is public. Use front-end variables for things like a public API URL, never for secret keys.
Common mistakes
- Forgetting to restart. Most apps read environment variables at startup. Change
.env, then restart the app or clear its config cache (in Laravel,php artisan config:clear). - Debug mode left on in production.
APP_DEBUG=trueon a live site can expose detailed errors and configuration. - Sharing
.envover chat or email. Use a password manager or a secrets tool to share credentials with teammates. - Same secrets everywhere. Use different database passwords and API keys for development, staging, and production.
Wrap-up
Environment variables and .env files separate your configuration from your code, which makes apps safer and easier to deploy in different places. Keep .env out of Git and out of your public folder, commit a .env.example instead, set variables through your server or platform's tools, and remember that anything in front-end code is public. Get these habits right and a leaked repository won't mean a leaked database.