typescriptintermediate
Environment Variable Validation with Zod
Validate environment variables at build time using Zod to catch misconfigurations early.
typescriptPress ⌘/Ctrl + Shift + C to copy
// lib/env.ts
import { z } from 'zod';
const envSchema = z.object({
// Server-only
DATABASE_URL: z.string().url(),
API_SECRET_KEY: z.string().min(32),
JWT_SECRET: z.string().min(16),
SMTP_HOST: z.string().optional(),
SMTP_PORT: z.coerce.number().default(587),
// Public (client-safe)
NEXT_PUBLIC_SITE_URL: z.string().url(),
NEXT_PUBLIC_GA_ID: z.string().startsWith('G-').optional(),
NEXT_PUBLIC_ADSENSE_CLIENT: z.string().startsWith('ca-pub-').optional(),
});
type Env = z.infer<typeof envSchema>;
function validateEnv(): Env {
const result = envSchema.safeParse(process.env);
if (!result.success) {
console.error('Environment variable validation failed:');
for (const [key, errors] of Object.entries(
result.error.flatten().fieldErrors
)) {
console.error(` ${key}: ${errors?.join(', ')}`);
}
throw new Error('Invalid environment variables');
}
return result.data;
}
export const env = validateEnv();
// Usage:
// import { env } from '@/lib/env';
// const dbUrl = env.DATABASE_URL; // Type-safe, validatedUse Cases
- build-time validation
- type-safe config
- preventing deployment errors
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptintermediate
Server Action Validation with Zod
Validate form data in server actions using Zod schemas with type-safe error handling.
Best for: contact forms
#nextjs#zod
typescriptintermediate
Type-Safe API Route Handler
Next.js App Router route handler with input validation, typed responses, and proper error handling.
Best for: CRUD API endpoints
#api#route-handler
typescriptintermediate
Server Action with Form Validation
Next.js Server Action handling form submissions with validation, error messages, and redirect on success.
Best for: Blog post creation
#server-actions#forms
typescriptintermediate
Next.js Server Actions with Forms
Use Server Actions for form handling with validation, optimistic updates, and error handling.
Best for: Form submissions without API routes
#nextjs#server-actions