Back to results for “Environment Variables & Configuration”
Next.js › Environment Variables & Configuration Management

How would you validate that all required environment variables are present and correctly formatted before your app starts?

Intermediate

Answer

You can write a small validation script or use a library like zod to define a schema for your expected environment variables, checking them once at startup and throwing a clear error immediately if anything is missing or malformed, rather than discovering the problem later through confusing runtime errors.
import { z } from 'zod';

const envSchema = z.object({
  DATABASE_URL: z.string().url(),
  API_SECRET_KEY: z.string().min(10)
});

envSchema.parse(process.env);
Real-world example A team adds environment variable validation to their build process, catching a typo in their database URL immediately during deployment instead of after the app was already live and failing for users.

Common follow-ups: What happens if validation fails during the build step?;Should this validation run in development, production, or both?