How to validate .env variables before deployment
Sometimes when we deploy our app in the server it crashes, we get 500 errors... The app works fine in localhost but crashes in the production server. Most of the time it is because we forget to include some ENV variables in the .env file during deployment.

To fix that, I found out that we can use a library called ZOD, a tool which validates if any environment variable is missing, and rejects the build if any of the variables are missing.
Steps to apply it in your app:
# npm
npm install zod
# yarn
yarn add zod
# pnpm
pnpm add zod
And the in your next.confit.ts file:
import { z } from "zod";
// ✅ Validate env variables before anything else runs
(() => {
const envSchema = z.object({
NEXT_PUBLIC_API_URL: z.string().url(),
FIREBASE_API_KEY: z.string().min(1),
NODE_ENV: z.enum(["development", "production", "test"]),
// Add more required env vars here
});
const parsed = envSchema.safeParse(process.env);
if (!parsed.success) {
console.error("❌ Invalid environment variables:");
console.error(parsed.error.flatten().fieldErrors);
process.exit(1); // ⛔ Kill the build!
}
console.log("✅ Env vars look good! You’re safe to ship 🚀");
})();
// ✅ Your regular Next.js config
/** @type {import('next').NextConfig} */
const nextConfig = {
// All your config here ...
};
export default nextConfig;#next.js
// vote00
