Environment variables let one JavaScript application use different settings in development, testing, and production. This guide provides a reusable checklist for storing configuration safely, handling browser and server boundaries, wiring values into builds and CI, and troubleshooting missing or stale settings without exposing secrets.
Overview
An environment variable is a named value supplied outside an application’s source code. Typical examples include an API base URL, a runtime mode, a feature flag, a database connection string, or a private service credential. The same application can then run against different services without editing its code for every environment.
The most important distinction is between public configuration and secret configuration. A browser application cannot keep a value secret if that value is included in its JavaScript bundle, exposed in a page, or sent to the browser during rendering. Public values may include a deliberately exposed API URL or analytics identifier. Private values include database credentials, signing keys, private API tokens, and service-account credentials; these belong on a server or in a protected build and deployment system.
In Node.js, runtime values are commonly read through process.env:
const port = Number(process.env.PORT || 3000);
const databaseUrl = process.env.DATABASE_URL;
if (!databaseUrl) {
throw new Error('DATABASE_URL is required');
}
Local .env files can make development convenient, often through a package such as dotenv or a runtime-supported environment-file option. The exact loading behavior depends on the Node.js version, framework, command, and deployment platform, so treat the project’s documented startup command as the source of truth.
Checklist by scenario
Local Node.js development
- Create a local environment file such as
.envor.env.localaccording to the framework’s convention. - Add matching placeholder names to
.env.example, but never add real credentials to that example file. - Keep local secret files out of version control with an appropriate
.gitignoreentry. - Load variables before application modules that read them, and validate required values during startup.
- Use explicit conversion for numbers and booleans. Environment variables arrive as strings, so
"false"should not accidentally be treated as a true value.
function required(name) {
const value = process.env[name];
if (!value) throw new Error(`Missing environment variable: ${name}`);
return value;
}
const config = {
port: Number(process.env.PORT || 3000),
nodeEnv: process.env.NODE_ENV || 'development',
sessionSecret: required('SESSION_SECRET')
};
Frontend applications and build tools
Frontend variables are usually substituted during a build. They are not a secure runtime vault. A tool may expose only variables with a particular prefix, such as VITE_, NEXT_PUBLIC_, PUBLIC_, or a project-specific convention. Older Create React App projects commonly use REACT_APP_. Confirm the convention for the exact framework and version rather than copying a prefix from another project.
- Use a clearly public prefix only for values safe to reveal to every visitor.
- Keep database URLs, private tokens, signing keys, and administrative credentials out of frontend-prefixed variables.
- Inspect the generated bundle or browser network requests when auditing what is exposed.
- Remember that changing a build-time value generally requires a new build and deployment.
- For a secret operation, call a server-side endpoint instead of moving the secret into browser code.
// Safe only if the URL is intentionally public
const apiBaseUrl = import.meta.env.VITE_PUBLIC_API_URL;
Server-side rendering and full-stack JavaScript
Full-stack frameworks may execute one module on both the server and the browser. Keep private configuration in server-only modules, and pass only deliberately selected public values across the rendering boundary. A variable named “public” is not protection by itself; the framework’s import rules, build process, and deployment mode determine what reaches the client.
Hosting and deployment environments
- Define production values in the hosting platform’s environment or secret settings rather than committing them to the repository.
- Separate development, preview, staging, and production values where the platform supports separate scopes.
- Check whether a variable is available at build time, runtime, or both.
- After changing a build-time variable, trigger the build again; restarting an already-built frontend may not change embedded values.
- Document which values are required for each deployment target and which are optional.
CI systems
CI pipelines normally distinguish ordinary variables from protected secrets. Store credentials in the CI system’s secret store, map them into the job only when needed, and limit them to trusted workflows. Avoid printing complete environment objects or running verbose commands that may reveal sensitive values.
# Illustrative CI configuration; adapt the syntax to your provider
steps:
- run: npm ci
- run: npm test
env:
DATABASE_URL: ${{ secrets.DATABASE_URL }}
NODE_ENV: test
Pull requests from untrusted branches may receive restricted secret access. Design tests so they can run without production credentials whenever possible.
What to double-check
- Names and prefixes: Confirm spelling, capitalization, required public prefixes, and whether the platform normalizes names.
- Loading order: Verify that the environment file is loaded before configuration is constructed. A correct file read too late is still a missing value.
- Scope: Identify whether the variable belongs to local development, a preview deployment, a server process, a build job, or the browser.
- Type conversion: Parse ports, timeouts, lists, and booleans deliberately. Validate allowed values instead of accepting any string.
- Precedence: Check which source wins when multiple files or platform settings define the same name. Framework conventions can differ.
- Exposure: Search compiled assets, source maps, logs, error messages, and client network requests for accidental disclosure.
- Rotation: If a secret has been committed or exposed, remove it from the codebase and rotate the credential through its provider. Deleting the line alone does not make an already-leaked credential safe.
A small configuration module is often safer than scattered calls to process.env. It creates one place for validation, defaults, type conversion, and documentation. Keep the module divided into server-only and browser-safe sections so imports make the boundary visible.
Common mistakes
- Putting secrets in frontend variables: Any value shipped to the browser should be considered public.
- Committing
.envfiles: Review ignore rules, repository history, pull requests, and generated archives. Use secret scanning as an additional check, not as a substitute for careful handling. - Assuming local behavior matches production: Local dotenv loading may not exist in the deployed process, and a hosting dashboard may inject values at a different phase.
- Changing a variable without rebuilding: Build-time substitution leaves old values in previously generated assets.
- Using unsafe defaults: Defaults can hide a failed deployment. Require critical production values and make non-production fallbacks explicit.
- Logging configuration for debugging: Log variable names or safe metadata, not complete values. Mask tokens, passwords, and connection strings.
- Relying on a package without checking its behavior: Before adding a configuration library, review its loading rules, maintenance status, and interaction with your runtime. A careful package review can prevent conflicting conventions.
When a deployment fails because a value is missing or stale, use this order: confirm the variable name in application code; check the file or platform scope; verify the build-versus-runtime phase; inspect the deployment’s effective configuration without printing secrets; rebuild or restart as appropriate; then test the resulting browser bundle and server behavior.
When to revisit
Review this checklist before adding a deployment target, moving from a client-only app to server rendering, introducing a new CI workflow, rotating credentials, or changing frontend build tools. It is also worth revisiting during regular seasonal planning cycles and after major runtime or framework upgrades, because environment-file loading, public-variable prefixes, and deployment syntax can change.
For a practical review, assign each variable four labels: owner, scope, phase (build or runtime), and sensitivity. Remove unused names, update .env.example, test a clean checkout, and confirm that production secrets are absent from browser assets and logs. Keep this inventory beside the project’s setup documentation so the next developer can configure the app without guessing.
Finally, repeat the deployment troubleshooting workflow after a toolchain change: run the application from a clean environment, execute the relevant tests, inspect safe configuration metadata, and verify one real request from the browser and one from the server. That short check catches most naming, scope, precedence, and stale-build problems before they become release issues.