Crash at boot, not on the first request
Why I validate all required env vars at server startup — and what it looks like in a Next.js App Router project.
The worst production incident I've been close to was a missing environment
variable that only surfaced when a customer triggered a specific code path at
2am. The error was Cannot read properties of undefined three stack frames deep
in an AWS SDK call. Took twenty minutes to figure out it was just a missing
S3_BUCKET in the deployment config.
The fix wasn't a better error message. It was moving the validation earlier.
Validate at module load time
// lib/env.ts
function required(key: string): string {
const value = process.env[key];
if (!value) throw new Error(`Missing required env var: ${key}`);
return value;
}
export const env = {
mongoUri: required('MONGODB_URI'),
s3Bucket: required('S3_BUCKET'),
smtpHost: required('SMTP_HOST'),
smtpUser: required('SMTP_USER'),
smtpPass: required('SMTP_PASS'),
sheetsId: required('GOOGLE_SHEETS_ID'),
};This module is imported by every route that needs config. If a variable is missing, the server throws at startup — before any request is served, before any customer hits an error, before the deploy looks like it succeeded.
In Next.js App Router
Next.js runs server components at request time, not at boot, which means module-
level code in a server component won't crash at startup — it'll crash on the
first render. Put your env module in a utility file and import it from
instrumentation.ts to force evaluation at server start:
// instrumentation.ts
export async function register() {
await import('./lib/env');
}Now a misconfigured deploy fails immediately and visibly, not silently on the first user.
The health endpoint
After boot validation, a GET /api/health endpoint that actively pings
downstream dependencies (MongoDB connect, SMTP handshake, Sheets API auth)
gives the load balancer something useful to check. 200 means the server
started and its dependencies are reachable. 503 means don't route here.
Two things, different jobs. Both worth having.