Next.js › Environment Variables & Configuration Management
How would you validate that all required environment variables are present and correctly formatted before your app starts?
IntermediateAnswer
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.