Environment configuration
ValidatedValidate process environment variables with Zod once at startup.
The environment configuration block parses process.env with a Zod schema and throws EnvValidationError when a value is missing or invalid. It runs once at startup, so the rest of your app gets a typed object instead of raw strings.
The block exports from its root index.ts. It does not load .env files.
Quick start
pnpm dlx blockend-cli init
pnpm dlx blockend-cli add env-configimport { z } from "zod";
import { parseEnv } from "@/blocks/env-config";
export const env = parseEnv(
z.object({
NODE_ENV: z.enum(["development", "test", "production"]).default("development"),
PORT: z.coerce.number().int().positive().default(3000),
DATABASE_URL: z.string().url(),
JWT_SECRET: z.string().min(32)
})
);
console.log(env.PORT); // numberIf DATABASE_URL is missing or is not a URL, startup fails with an error that lists every invalid field.
Files
env-config/
├── index.ts
└── index.test.tsInstallation
The block depends on Zod. The CLI installs it if it is missing.
pnpm dlx blockend-cli add env-configFor a manual install, copy index.ts into blocks/env-config:
import { z, ZodType } from "zod";
/**
* Thrown when environment variable validation fails.
*
* This error is designed to fail fast during application startup,
* preventing the application from running with an invalid configuration.
*/
export class EnvValidationError extends Error {
public readonly issues: readonly z.core.$ZodIssue[];
constructor(issues: readonly z.core.$ZodIssue[]) {
const formattedIssues = issues
.map(({ path, message }) => ` • ${path.length ? path.join(".") : "(root)"} → ${message}`)
.join("\n");
super(
[
"",
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"❌ Environment Configuration Validation Failed",
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
formattedIssues,
"",
"Please verify your environment variables before restarting.",
""
].join("\n")
);
this.name = "EnvValidationError";
this.issues = issues;
Object.setPrototypeOf(this, new.target.prototype);
Object.freeze(this);
}
}
/**
* Validates and parses environment variables using a Zod schema.
*
* The application should invoke this function exactly once during startup.
* If validation fails, an {@link EnvValidationError} is thrown immediately,
* ensuring the application never starts with an invalid configuration.
*
* @template T
* The inferred type of the validated environment object.
*
* @param schema
* Zod schema describing the expected environment variables.
*
* @param source
* Environment source to validate.
* Defaults to `process.env`.
*
* @returns
* Fully validated and strongly typed environment configuration.
*
* @throws {EnvValidationError}
* When one or more environment variables are missing or invalid.
*/
export function parseEnv<T>(
schema: ZodType<T>,
source: NodeJS.ProcessEnv | Record<string, string | undefined> = process.env
): T {
const result = schema.safeParse(source);
if (!result.success) {
throw new EnvValidationError(result.error.issues);
}
return result.data;
}
Loading .env files
The block reads process.env by default. It does not import dotenv and does not read a file.
Use the runtime's environment loader:
node --env-file=.env dist/server.jsNode 20.6 and later support --env-file. In production, set variables through your platform's secret manager or container environment.
If you already use dotenv, load it before importing the module that calls parseEnv:
import "dotenv/config";
import { env } from "./config/env";Order matters. parseEnv reads the environment when your config module runs. Loading .env after that is too late.
Usage
Define a schema
import { z } from "zod";
import { parseEnv } from "@/blocks/env-config";
const schema = z.object({
NODE_ENV: z.enum(["development", "test", "production"]).default("development"),
PORT: z.coerce.number().int().positive().default(3000),
DATABASE_URL: z.string().url(),
REDIS_URL: z.string().url().optional(),
JWT_SECRET: z.string().min(32)
});
export const env = parseEnv(schema);Zod coercion turns strings into numbers and booleans:
z.coerce.boolean(); // "false" becomes true
z.coerce.number(); // "3000" becomes 3000z.coerce.boolean() treats any non-empty string as true, including "false". Use an enum for boolean flags:
FEATURE_X: z.enum(["true", "false"])
.default("false")
.transform((value) => value === "true");Test with a custom source
parseEnv accepts a second argument, so tests do not need to mutate process.env:
import { parseEnv } from "@/blocks/env-config";
const env = parseEnv(schema, {
NODE_ENV: "test",
PORT: "4000",
DATABASE_URL: "postgres://localhost/test",
JWT_SECRET: "test-secret-with-at-least-32-characters"
});Catch validation errors
import { EnvValidationError, parseEnv } from "@/blocks/env-config";
try {
const env = parseEnv(schema);
} catch (error) {
if (error instanceof EnvValidationError) {
console.error(error.issues);
process.exit(1);
}
throw error;
}issues is the raw Zod issue array. The error message is formatted for terminal output.
API reference
parseEnv
function parseEnv<T>(
schema: z.ZodType<T>,
source?: NodeJS.ProcessEnv | Record<string, string | undefined>
): T;schema.safeParse runs against source. The default is process.env. On success you get the parsed object. On failure you get EnvValidationError.
EnvValidationError
class EnvValidationError extends Error {
readonly issues: readonly z.core.$ZodIssue[];
}The instance is frozen. The message lists each failing path and its validation message.
Behavior
- Validation runs when you call
parseEnv, not at import time. - All fields are validated in one pass. You get every issue, not just the first one.
- Defaults and transforms from the Zod schema are applied.
- Unknown keys in the environment are ignored because the default Zod object strips them.
- The returned object is a plain object. It is not re-read when the environment changes.
Production notes
- Call
parseEnvonce in a config module and import that module everywhere else. - Do not pass secrets to client bundles or log the parsed object.
z.string().url()accepts any scheme the URL parser accepts. If your database driver also accepts non-URL connection strings, add a custom refinement.- Keep
.envout of version control. The block does not manage secrets. - Validate
NODE_ENVexplicitly if behavior changes between environments.
When not to use it
- Your platform validates configuration before the process starts.
- You prefer a different validation library.
- You need configuration that changes at runtime. This block reads once at startup.
Related blocks
- Token service reads signing keys and token settings from your config.
- Password hash reads the pepper from an environment variable.
- Health check can report configuration failures at startup.