Advanced Node.js Interview QuestionsAdvancedScenario
Node.js · Question 96
How would you validate environment configuration at startup?
Direct answer
Parse process.env with Zod or envalid schema at boot — fail fast with clear missing var message; export typed config object; commit .env.example; never read process.env scattered across modules.
Scenario: API must not start with missing DATABASE_URL or JWT_SECRET — catch misconfiguration before accepting traffic (Q48).
- Single config module — apps/api/src/config.ts imported first.
- Zod schema — z.string().url(), z.coerce.number(), enums for NODE_ENV.
- Fail fast — process.exit(1) with formatted Zod error.
- No secrets in logs — log which keys missing, not their values.
scenario-env-validation.mjs
import { z } from "zod";
const envSchema = z.object({
NODE_ENV: z.enum(["development", "test", "production"]).default("development"),
PORT: z.coerce.number().default(4000),
DATABASE_URL: z.string().url(),
JWT_SECRET: z.string().min(32),
REDIS_URL: z.string().url().optional(),
});
const parsed = envSchema.safeParse(process.env);
if (!parsed.success) {
console.error("Invalid environment:", parsed.error.flatten().fieldErrors);
process.exit(1);
}
export const config = parsed.data;