A missing variable used to surface as a 500 on one page in production. Now the app refuses to start and names the variable. Import this from your root layout so it runs on every server boot. Any validator works, zod is just what I had.
Snippet
Copied 9 times
// lib/env.ts
import { z } from "zod";
const schema = z.object({
NEXT_PUBLIC_SUPABASE_URL: z.string().url(),
NEXT_PUBLIC_SUPABASE_ANON_KEY: z.string().min(1),
SUPABASE_SERVICE_ROLE_KEY: z.string().min(1),
STRIPE_SECRET_KEY: z.string().startsWith("sk_"),
});
const parsed = schema.safeParse(process.env);
if (!parsed.success) {
console.error(parsed.error.flatten().fieldErrors);
throw new Error("Missing or invalid environment variables");
}
export const env = parsed.data;