Environment variables are runtime input, not automatically type-safe configuration. This guide shows how to declare, validate, and expose them safely in TypeScript applications, with reusable patterns for Node.js, Vite, Next.js, and Docker deployments.
Overview
TypeScript cannot prove that an environment variable exists at runtime. In Node.js, values from process.env are typically typed as optional strings, so a value may be missing, empty, malformed, or incorrectly named even when the code compiles. A reliable configuration design therefore has three layers:
- Declare the shape: Tell TypeScript which configuration keys your application expects.
- Validate at the boundary: Check required values and formats when the process starts, rather than discovering a problem deep inside a request handler.
- Control exposure: Keep server-only secrets away from browser bundles, public configuration, logs, and client-side telemetry.
A useful rule is to read environment variables once in a configuration module and export a validated object. Application code should import config.databaseUrl or config.port, rather than repeatedly reading process.env. This creates a narrow, searchable boundary and makes tests easier to configure.
Do not confuse a TypeScript declaration with validation. A declaration file can improve editor support for a tool such as Vite, but it does not create a missing variable or verify its value. Runtime validation remains necessary.
For broader configuration work, the same boundary principle fits alongside strict compiler settings described in this TypeScript tsconfig guide. If configuration affects test startup, also compare the environment-loading behavior of your test runner in the TypeScript testing setup guide.
Checklist by scenario
Node.js and Express applications
Load the environment file before importing modules that construct clients, connect to databases, or read configuration. Then validate the values in one module.
import 'dotenv/config';
import { z } from 'zod';
const envSchema = z.object({
NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
PORT: z.coerce.number().int().positive().default(3000),
DATABASE_URL: z.string().min(1),
SESSION_SECRET: z.string().min(32),
});
const parsed = envSchema.safeParse(process.env);
if (!parsed.success) {
console.error('Invalid environment configuration', parsed.error.flatten().fieldErrors);
process.exit(1);
}
export const config = parsed.data;
The validation library is interchangeable; the important pattern is that parsing happens once and the exported result is typed from the schema. Avoid exporting the entire environment object. Exposing only the keys the server needs reduces accidental use of undeclared configuration.
- Confirm the environment file is loaded in development and test processes.
- Keep production secrets in the deployment platform’s secret store or protected environment settings.
- Validate URLs, numeric ranges, enum values, and credential lengths instead of checking only for presence.
- Do not print complete values when reporting validation errors.
Vite applications
Vite exposes variables intended for browser code through a configured public prefix. In the common setup, only variables beginning with VITE_ are available through import.meta.env. Treat every such value as public: users can inspect it in the built application.
interface ImportMetaEnv {
readonly VITE_API_BASE_URL: string;
readonly VITE_APP_ENV: 'development' | 'preview' | 'production';
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}
This declaration improves autocomplete, but it does not validate the deployed build. Add a small startup or build-time check for required public variables, and never place database passwords, private tokens, signing keys, or service credentials behind the public prefix.
Next.js applications
Separate server configuration from browser configuration. In Next.js, variables intended for client-side use commonly require the NEXT_PUBLIC_ prefix. A prefixed value should be considered public because it can be embedded into browser-delivered code. Server-only values should be read in server modules, route handlers, server actions, or other server execution paths and should not be passed to client components.
Keep the distinction visible in code. For example, a server configuration module might export DATABASE_URL and AUTH_SECRET, while a client configuration module exports only NEXT_PUBLIC_API_BASE_URL. If a value must cross the server-client boundary, make that transfer explicit and provide the smallest possible derived value rather than forwarding the complete environment object.
Docker deployments
Decide whether a value is needed while building the image or only when the container starts. Public frontend variables are often embedded during a build, while server secrets should normally be supplied at runtime. The exact mechanism depends on the deployment platform, but the checklist is stable:
- Do not copy local secret files into the image unless there is a deliberate, reviewed reason.
- Use a suitable ignore file and review the image build context.
- Pass runtime secrets through the orchestrator or deployment platform, not through source control.
- Run the same startup validation inside the container that you use locally.
- Check whether build arguments, generated assets, or logs could preserve a supposedly private value.
Framework comparison
| Environment | Typical access | Public-value rule | Recommended validation point |
|---|---|---|---|
| Node.js | process.env | Nothing is public merely because it is an environment variable; protect server values. | Process startup, before app initialization |
| Vite | import.meta.env | Values using the public prefix are bundled for browser access. | Build or application startup |
| Next.js | process.env on the server; prefixed values may reach the client | Prefixed values are public and should contain no secrets. | Server startup and explicit client configuration checks |
| Docker | Injected by the image, container, or platform | Build-time values can persist in layers or assets; runtime values remain deployment inputs. | Image build review plus container startup |
What to double-check
Before adding a variable, use this required-variable checklist:
- Name: Does the spelling match the framework, deployment manifest, and code?
- Scope: Is it server-only, public client configuration, build-time input, or runtime input?
- Presence: Should an empty string be rejected, or is an empty value meaningful?
- Type: Are numbers, booleans, URLs, arrays, and JSON values parsed rather than treated as raw strings?
- Environment: Is the value defined consistently for development, test, preview, and production?
- Failure behavior: Does the process fail early with a useful but non-sensitive error?
- Rotation: Can the secret be replaced without changing application source code?
- Tests: Can tests provide an isolated configuration without mutating a developer’s real environment?
Use explicit schemas for values with structure. For example, parse a comma-separated allowlist into an array, validate an API URL with the URL type supported by your chosen library, and coerce port values to numbers. Be careful with booleans: the string 'false' is truthy in JavaScript, so a simple cast can produce the opposite behavior from what you intended.
Keep configuration modules near a clear application boundary rather than exporting them from a broad barrel file. That makes server-only imports easier to audit. The principles in this module boundaries guide are especially useful when a shared package contains both browser and server code.
Common mistakes
- Using non-null assertions everywhere:
process.env.API_KEY!silences TypeScript but does not verify the value. Validate once and export a known-good configuration instead. - Committing secret files: A file in
.gitignoreis not protection if it was already committed or copied into an image layer. Check repository history and build context when handling an exposure. - Assuming prefixes protect secrets: Public prefixes are routing conventions, not encryption. Anything exposed to client code should be assumed visible.
- Validating only in local development: A local fallback can hide a missing production setting. Keep required production fields required and use separate, intentional defaults for local work.
- Loading too late: Importing a database client before configuration is loaded can capture undefined values. Establish the load-and-validate order at the entry point.
- Logging the whole environment: Debug output, error reports, and startup logs can become an accidental secret-disclosure channel. Log variable names or redacted diagnostics only.
- Sharing server config with client code: A common TypeScript type does not make a value safe to send to the browser. Separate public and private objects as well as their modules.
When to revisit
Return to this checklist whenever a workflow or tool changes, before a seasonal planning or release cycle, and whenever you add an environment. It is particularly useful before migrating from Node.js to a framework, introducing a preview deployment, moving from a local process to Docker, or changing how secrets are injected.
Recheck framework prefixes and environment-loading behavior when upgrading Vite or Next.js, changing build adapters, or replacing a deployment platform. Recheck validation-library syntax when upgrading that dependency rather than copying an old example blindly. Review the build output whenever a variable changes from server-only to client-visible.
For a practical final pass, list every variable, classify its scope, identify its source in each environment, and locate its validation. Then build from a clean checkout, start the application with one required value removed, and confirm that it fails clearly before serving traffic. Finally, inspect logs and generated assets for accidental values. This small exercise turns type-safe environment variables from a declaration exercise into a repeatable operational safeguard.