Next.js Discord

Discord Forum

How to validate env variables with zod?

Unanswered
Paper wasp posted this in #help-forum
Open in Discord
Paper waspOP
Hi, I'm trying to validate my env variables with zod.
I create this env.ts file
import { z } from "zod";

const envServerSchema = z.object({
    BETTER_AUTH_SECRET: z.string().min(1, "BETTER_AUTH_SECRET is required"),
    DATABASE_URL: z.string().min(1, "DATABASE_URL is required"),
});

const { success: successServer, error: errorServer, data: dataServer } = envServerSchema.safeParse(await process.env);

const envPublicSchema = z.object({
    NEXT_PUBLIC_BETTER_AUTH_URL: z.string().min(1, "BETTER_AUTH_URL is required"),
    NEXT_PUBLIC_ROOT_DOMAIN: z.string().url().min(1, "NEXT_PUBLIC_ROOT_DOMAIN is required"),
    NEXT_PUBLIC_VERCEL_DEPLOYMENT_SUFFIX: z.string().optional()
});

const { success: successPublic, error: errorPublic, data: dataPublic } = envPublicSchema.safeParse(await process.env);



if (!successServer) {
    console.error("Invalid environment on server variables:", errorServer?.format());
    throw new Error("Invalid environment on server variables");
}

if (!successPublic) {
    console.error("Invalid environment on public variables:", errorPublic?.format());
    throw new Error("Invalid environment on public variables");
}


export const {
    BETTER_AUTH_SECRET,
    DATABASE_URL,
} = dataServer;

export const {
    NEXT_PUBLIC_BETTER_AUTH_URL,
    NEXT_PUBLIC_ROOT_DOMAIN,
    NEXT_PUBLIC_VERCEL_DEPLOYMENT_SUFFIX,
} = dataPublic;

I tried to separate public from private to avoid the errors, but I couldn't fix it.
Client side I got the invalid enviroment server variable triggered, even when any server env is used on the client.
Sounds like every variable is validated, and because of client side didn't have access to server variables, it throw an error.
What is the correct approach?

PS: I'm using them by importing as import { VAR } from '@env'.
I'm importing all the exported variables in next.config.js so they get initialized.

Thanks in advance and happy new year

1 Reply

Asian black bear
Do yourself a favor and don't reinvent the wheel and use this superb solution: https://env.t3.gg