Environment variables give a web application different settings in development, testing, and production without changing its source code. This guide provides a reusable local-to-production workflow for defining configuration, separating public values from secrets, validating required variables, and checking that deployment systems load the intended values safely.
Overview
A configuration value belongs in an environment variable when it may change between environments or should not be hard-coded into the application. Typical examples include database connection details, API endpoints, logging levels, feature flags, encryption keys, and third-party credentials.
Environment variables are a delivery mechanism, not a complete secrets-management strategy. A value can still be exposed if it is printed in logs, committed to source control, included in a browser bundle, or copied into an error report. Treat every value according to its sensitivity and its runtime audience.
A safe workflow has five parts:
- Define the configuration contract: names, types, defaults, and whether each value is public or server-only.
- Provide a non-secret example file so developers know what is required.
- Load variables using the conventions of the selected runtime or framework.
- Validate configuration at startup or build time rather than discovering missing values through a user request.
- Inject production values through the deployment platform, CI system, or a managed secret store.
Keep the application code independent of the storage mechanism where possible. The application should ask for a configuration value; the local shell, container, CI job, or cloud runtime should supply it.
Checklist by scenario
1. Start with a configuration contract
Before creating a .env file, list the values the application actually needs. Record the variable name, required format, owner, sensitivity, and whether it is consumed by the server, build process, browser, or more than one.
# Configuration contract
APP_ENV=development
PORT=3000
PUBLIC_API_BASE_URL=https://api.example.test
DATABASE_URL=postgres://user:password@host/database
SESSION_SECRET=replace-with-a-long-random-value
LOG_LEVEL=info
This is a planning example, not a file to copy with real credentials. Use clear names that communicate scope. A prefix such as PUBLIC_, VITE_, or another framework-defined convention may mark values for browser exposure, but the exact rule depends on the toolchain. Verify the framework documentation before relying on a prefix.
2. Commit an example file, not a secret file
Commit a file such as .env.example containing variable names and safe placeholder values. Do not place working credentials in it. Keep the real local file, commonly .env.local or .env, outside source control and list it in .gitignore.
# .env.example
APP_ENV=development
PORT=3000
PUBLIC_API_BASE_URL=http://localhost:4000
DATABASE_URL=
SESSION_SECRET=
LOG_LEVEL=debug
Use a documented setup command or onboarding note to explain how developers create their local file. If the project supports multiple services, give each service a clear configuration boundary rather than sharing one oversized file by default.
3. Separate public configuration from server-only values
Anything shipped to a browser should be considered public. This includes values embedded into JavaScript during a frontend build, even if the original value came from a protected CI secret. Public configuration may include a browser API base URL, a public analytics identifier, or a feature setting intended for users.
Server-only values include database credentials, private API keys, signing secrets, encryption keys, and privileged service tokens. Keep these in backend code or server-side runtime configuration. Never use a private secret as a substitute for frontend access control; browser users can inspect network requests and downloaded assets.
4. Load variables according to the runtime
Loading behavior varies. A Node.js process may receive values from the shell or a dotenv-compatible loader. Containers commonly receive them through the container environment or an orchestration manifest. Frontend build tools often read selected variables at build time and replace references in the generated assets. Serverless platforms may expose values to functions through deployment configuration.
Check four details for each runtime:
- Which filenames and naming prefixes are recognized?
- Are values read at build time, startup, request time, or a combination?
- Which environment wins when the same variable appears in multiple places?
- Will changing a value require a rebuild, restart, or new deployment?
Do not assume that a variable changed in the hosting dashboard is immediately visible to a running process or an already-built frontend. Confirm the lifecycle with a harmless test value in a non-production environment.
5. Validate required values before serving traffic
Fail early when required configuration is missing or malformed. Validation should check presence and, where useful, type, URL format, allowed values, and relationships between values. Avoid logging the value itself when reporting a validation error.
const required = ["DATABASE_URL", "SESSION_SECRET"];
for (const name of required) {
if (!process.env[name]) {
throw new Error(`Missing required configuration: ${name}`);
}
}
const port = Number(process.env.PORT || 3000);
if (!Number.isInteger(port) || port < 1) {
throw new Error("PORT must be a valid positive integer");
}
Use the validation approach appropriate to the language and framework. The important behavior is consistent: configuration errors should be visible during startup or deployment, not after a customer triggers an endpoint.
6. Choose the right production source
| Source | Best use | Double-check |
|---|---|---|
| Local environment file | Developer-specific settings and local services | It is ignored by Git and contains no copied production credentials |
| CI secret or protected variable | Supplying values during tests, builds, and deployments | Access is limited, masking is enabled where available, and scripts do not echo values |
| Managed cloud configuration or secret store | Runtime production settings and secret rotation | Application identity has only the permissions it needs and values are scoped to the correct environment |
Keep deployment configuration close to the infrastructure process, but do not place secret values in a Dockerfile or ordinary infrastructure code. For container build and deployment checks, see Dockerfile Best Practices for Cloud Deployments. For CI-specific troubleshooting, see the GitHub Actions Debugging Guide.
What to double-check
- Variable names: Confirm spelling, capitalization, underscores, and prefixes. Names are often case-sensitive.
- Whitespace and quoting: Check how the selected loader handles spaces, quotes, multiline values, and special characters. Connection strings and certificates deserve particular care.
- Build versus runtime: Determine whether the value is compiled into an asset or read by a server process. A runtime change cannot alter a value already baked into static files.
- Environment boundaries: Verify that local, preview, staging, and production values are not being mixed by a shared project, branch rule, or deployment target.
- Logs and diagnostics: Inspect startup messages, request traces, crash reports, and CI output for accidental values. Log variable names or safe status indicators instead of contents.
- Access scope: Give deployment identities and applications only the configuration access they require. A service that needs one API key should not automatically receive every secret.
- Rotation behavior: Know how to replace a credential, restart affected services, invalidate the old value, and verify that the new value is active.
When debugging an API integration, first confirm that the server received the intended non-secret endpoint and environment. Then inspect request status, headers, and response structure without copying credentials into a shared ticket or online tool. The API Testing with curl guide provides a useful request-debugging workflow.
Common mistakes
Committing a real secret
Removing a secret from the latest commit does not necessarily remove it from repository history, caches, or clones. If a credential was exposed, treat it as compromised: revoke or rotate it, investigate where it appeared, and then clean up the repository according to your source-control process.
Assuming .gitignore is protection against every leak
Ignore rules help prevent accidental commits, but they do not protect shell history, terminal recordings, screenshots, logs, copied configuration, or a developer's backup system. Use secret scanning where available and review the paths that handle configuration.
Putting server secrets in frontend variables
A variable name that sounds private is not private once it reaches the browser. Inspect the production bundle and browser network requests when introducing a new frontend setting. Keep authorization decisions on the server.
Using silent defaults for dangerous settings
Defaults are useful for harmless local values such as a development port or log level. They are risky for database targets, signing keys, payment endpoints, or access controls because a typo can direct an application to the wrong system. Make sensitive values required and explicit.
Changing a value without restarting or rebuilding
Configuration may be captured when a process starts or when a frontend is built. If a change appears ineffective, check the application lifecycle, deployment revision, and active environment before changing the code.
When to revisit
Use this workflow before every new environment, deployment, and secret rotation. Revisit it during seasonal planning cycles, after a framework or hosting change, and whenever the team adds a service, build step, CI workflow, or third-party integration.
A practical review checklist is:
- Compare the configuration contract with the variables the application reads today.
- Regenerate the example file and verify that it contains no usable credentials.
- Test startup validation in a clean environment with one required value intentionally missing.
- Trace one public value and one server-only value through local development, CI, deployment, and runtime behavior.
- Review logs, build artifacts, browser bundles, and repository history for accidental exposure.
- Document the rotation owner, replacement steps, restart or rebuild requirement, and rollback plan.
Keep the checklist with the application documentation and update it when workflows or tools change. A small, current configuration contract is easier to review than a collection of undocumented files and dashboard entries—and it gives every deployment a clear, repeatable path from local development to production.