Environment Variable Validation
Validate required environment variables at build time with type-safe access and descriptive errors.
function requireEnv(key: string): string {
const value = process.env[key];
if (!value) {
throw new Error(
`[env] Missing required environment variable: ${key}`
);
}
return value;
}
export const env = {
DATABASE_URL: requireEnv('DATABASE_URL'),
NEXTAUTH_SECRET: requireEnv('NEXTAUTH_SECRET'),
NEXTAUTH_URL: requireEnv('NEXTAUTH_URL'),
STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY ?? '',
ANALYTICS_ID: process.env.NEXT_PUBLIC_ANALYTICS_ID ?? '',
} as const;
// Validate at import time — fails fast during build
// import { env } from '@/lib/env';Use Cases
- App startup checks
- CI pipeline validation
- Config management
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
Environment Variable Validator
Validates required environment variables at startup and returns a typed config object or throws with missing keys.
Type-Safe Settings with Pydantic
Load and validate environment variables into a typed settings object using pydantic-settings with defaults.
Type-Safe API Route Handler
Next.js App Router route handler with input validation, typed responses, and proper error handling.
Server Action with Form Validation
Next.js Server Action handling form submissions with validation, error messages, and redirect on success.