Environment variables keep configuration out of application code, but only when each environment loads, validates, and protects them consistently. This guide provides a reusable checklist for local development, testing, CI, containers, frontend builds, and production deployments, with practical templates for Node.js, Python, PHP, and browser applications.
Overview
An environment variable is a named value supplied to a process at runtime or build time. Typical examples include database connection details, API base URLs, feature flags, log levels, and credentials. The application reads a variable by name instead of relying on a value embedded in source code.
A .env file is one convenient way to provide variables during local development. It is not, by itself, a secrets manager. Treat it as a configuration input that must be excluded from version control, access-controlled, and replaced by a safer mechanism where the deployment environment supports one.
The most reliable configuration design separates three concerns:
- Names: A stable contract such as
DATABASE_URLorLOG_LEVEL. - Values: Different values for local, test, staging, and production environments.
- Delivery: The mechanism that supplies values, such as a shell, CI secret store, container runtime, or hosting dashboard.
Keep the names stable across environments whenever possible. A missing or misspelled variable should fail during startup or deployment rather than producing a confusing error later. For related configuration work, see the API debugging workflow and the .gitignore reference.
Configuration methods at a glance
| Method | Best use | Important check |
|---|---|---|
.env file | Local development and documented examples | Ignore real files; provide a safe example file |
| Shell export | One-off commands, scripts, and local overrides | Confirm the variable is available to the child process |
| Docker Compose | Local multi-service development | Distinguish interpolation from values passed into the container |
| GitHub Actions | Tests, builds, and deployments | Use repository, environment, or organization secrets appropriately |
| Hosting platform settings | Staging and production runtime configuration | Check whether a value is available at build time, runtime, or both |
| Framework configuration | Loading and exposing values inside an application | Validate the framework’s naming and public-variable rules |
Checklist by scenario
Starting a project
- Define an uppercase naming convention with underscores, such as
PAYMENTS_API_URL. Avoid ambiguous names likeKEYorURL. - Create
.env.examplewith variable names, harmless placeholders, and short comments where needed. Never copy real credentials into this file. - Add local secret files to
.gitignore. Review the ignore rule before creating a commit; an ignore pattern does not remove a file that is already tracked. - Document which values are required, which are optional, and which are public. Record expected formats, such as a full URL, integer, Boolean, or comma-separated list.
- Validate configuration once at application startup and expose a typed or normalized configuration object to the rest of the codebase.
Local development and testing
Use a local .env file for values that should not be committed, and use a separate test configuration for automated tests. Test data should not depend on a developer’s personal credentials or production services.
A shell export is useful for a temporary override:
LOG_LEVEL=debug npm run dev
export API_BASE_URL="http://localhost:4000"
Check the process that actually starts the application. A variable set in one terminal, IDE configuration, package script, or container may not be available to another. If a test runner loads a different configuration file, make that behavior explicit in the project documentation.
Node.js
Load local variables using the configuration mechanism supported by your application or framework, then validate them before serving requests. With a dotenv-style setup, a minimal entry point can look like this:
import 'dotenv/config';
const required = ['DATABASE_URL', 'SESSION_SECRET'];
for (const name of required) {
if (!process.env[name]) {
throw new Error(`Missing required environment variable: ${name}`);
}
}
export const config = {
databaseUrl: process.env.DATABASE_URL,
sessionSecret: process.env.SESSION_SECRET,
port: Number(process.env.PORT || 3000)
};
Do not assume that a value is a string in the form your code expects. Convert ports, timeouts, and Boolean flags deliberately, and reject invalid values rather than silently using an unsafe default.
Python
A Python application can read process variables directly. A dotenv package may be used for local development, but production should receive configuration through the deployment environment or an approved secret mechanism.
import os
def required(name: str) -> str:
value = os.getenv(name)
if not value:
raise RuntimeError(f"Missing required environment variable: {name}")
return value
DATABASE_URL = required("DATABASE_URL")
DEBUG = os.getenv("DEBUG", "false").lower() == "true"
PORT = int(os.getenv("PORT", "8000"))
Keep configuration loading in one module instead of scattering os.getenv calls throughout the application. This makes validation and testing easier.
PHP
PHP applications commonly read values with getenv. If a dotenv library is used, load it early in the bootstrap process and ensure production files are not committed or web-accessible.
<?php
function required_env(string $name): string {
$value = getenv($name);
if ($value === false || $value === '') {
throw new RuntimeException("Missing required environment variable: {$name}");
}
return $value;
}
$config = [
'database_url' => required_env('DATABASE_URL'),
'app_env' => getenv('APP_ENV') ?: 'development',
];
Frontend builds
Browser code cannot keep a value secret once it has been bundled and sent to users. Public API base URLs, analytics identifiers, and feature settings may be embedded in a frontend build; private keys, database credentials, signing secrets, and privileged tokens must remain on a server.
Frameworks often require a naming prefix before exposing a variable to client-side code. Treat that prefix as an exposure boundary, not a security feature. Confirm whether the variable is substituted during the build or read at runtime, because changing a hosting setting after a static build may not change the already-generated assets.
Containers and Docker Compose
Compose can substitute values into a configuration file and can also pass values into a container. These are related but distinct operations. Verify the final container environment rather than assuming that a value used in interpolation is available inside the application process.
services:
api:
build: .
environment:
DATABASE_URL: ${DATABASE_URL}
LOG_LEVEL: ${LOG_LEVEL:-info}
Do not bake credentials into a Docker image layer. Supply deployment secrets through the container platform’s supported secret or environment configuration, and limit which services receive each value.
CI/CD and production
In GitHub Actions, keep non-sensitive configuration in workflow variables when appropriate and store credentials in repository, organization, or environment secrets according to the project’s access model. Pass only the values needed by each job.
jobs:
test:
runs-on: ubuntu-latest
env:
APP_ENV: test
DATABASE_URL: ${{ secrets.TEST_DATABASE_URL }}
steps:
- uses: actions/checkout@v4
- run: npm ci
- run: npm test
For a hosting platform, configure variables in the project or service settings, then check the platform’s distinction between build-time variables, runtime variables, preview environments, and production environments. The exact interface changes between providers, so verify the current deployment behavior whenever you change platforms or build architecture.
What to double-check
- Required values: Does startup fail with a clear message when a required variable is absent?
- Types and formats: Are ports numeric, URLs valid, lists parsed consistently, and Boolean values interpreted explicitly?
- Scope: Is each variable available only to the process, job, service, or environment that needs it?
- Public versus private: Could a browser user, build artifact, log, error report, or client-side source map reveal the value?
- Precedence: If multiple files or delivery methods are present, which one wins? Document the order rather than relying on guesswork.
- Escaping: Do passwords, multiline keys, dollar signs, spaces, and special characters survive parsing correctly?
- Logs: Are configuration objects, request headers, database URLs, and exception messages redacted before logging?
- Rotation: Can a credential be replaced without changing application code? Identify who owns the replacement and where the new value is installed.
If a secret has entered Git history, removing the current file is not enough. Revoke or rotate the credential first, then clean the repository history using an established procedure and coordinate with anyone who may have cloned the repository. A repository cleanup does not make an exposed credential trustworthy again.
Common mistakes
- Committing
.env: Add ignore rules before creating local files and inspect staged changes before pushing. - Using a secret in frontend code: Anything shipped to the browser should be considered public, even if its variable name suggests otherwise.
- Relying on silent defaults: A fallback can hide a broken deployment. Use defaults only when the behavior is genuinely safe and intentional.
- Mixing environment names: Choose one spelling, such as
DATABASE_URL, and use it in code, examples, CI, containers, and hosting settings. - Assuming local behavior matches production: Local dotenv loading, CI injection, container startup, and hosting builds may follow different precedence rules.
- Printing the entire environment: Debugging with an environment dump can disclose credentials in terminal history, CI logs, or monitoring systems.
- Sharing one credential everywhere: Separate local, test, staging, and production access so a compromise or rotation has a limited scope.
When to revisit
Use this checklist whenever you start a project, add a deployment environment, onboard a teammate, migrate to containers, change frontend build tooling, or investigate a “works locally” configuration failure. Revisit it before a production release and after any incident involving credentials or logs.
Also review configuration when a framework, CI provider, hosting platform, or runtime changes its loading behavior. Build-time versus runtime injection is especially important when moving from a server-rendered application to static assets, adding preview deployments, or changing the container entry point.
A practical final review is:
- Compare
.env.examplewith the variables used by the application. - Run the test suite with required values missing and with deliberately invalid values.
- Inspect CI and hosting settings for each environment separately.
- Search the repository, build output, logs, and documentation for accidental secret exposure.
- Confirm that a credential can be rotated and that old values are revoked.
- Record the configuration contract so the next developer can reproduce the setup without receiving a secret through an unsafe channel.
For adjacent workflow tasks, you can also consult the JSON formatter and validator guide when checking structured configuration, or the JWT decoder guide when troubleshooting token claims without treating decoding as signature validation.