Demo, all content is generated
Share

Fail the boot when an environment variable is missing

Open · 166 views · asked by lena_ops · edited

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;
Comment
Same pattern in every app I ship. Fail loudly at boot. jonas_k · edited
Tweak I made: a separate schema for the NEXT_PUBLIC_ ones in the client, so the server-only keys never get referenced from client code. ximena_c · edited

Activity