Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating environment variables in Next.js with Zod

Maybe the resolution is quite simple, but I've been stagnating on it all day.

I'm validating my environment variables with the zod library, which is very famous for validating and transforming data, but I'm getting a persistent error that my environment variables are invalid.

Image of the error:

enter image description here

My validation scheme:

import { z } from 'zod'

const envSchema = z.object({
  SUPABASE_URL: z.string().url(),
  SUPABASE_KEY: z.string().min(1),
})

const envParsed = envSchema.safeParse(process.env)

if (envParsed.success === false) {
  console.error('❌ Invalid environment variables', envParsed.error.format())

  throw new Error('Invalid environment variables.')
}

export const env = envParsed.data

My environment file is .env.local and it has the definitions of my variables.

Example:

enter image description here

like image 731
patrick-ts Avatar asked Aug 31 '25 01:08

patrick-ts


1 Answers

I've come across the same issue. It seems that public environment variables are bundled differently in nextjs, like at compile time. I ended up making it work by explicitly referencing the public variables like so:

// lib/env/client.ts

'use client';

const envSchema = z.object({
  NEXT_PUBLIC_MY_VARIABLE: z.string(),
})

export default envSchema.parse({
  NEXT_PUBLIC_MY_VARIABLE: process.env.NEXT_PUBLIC_MY_VARIABLE,
});

Then, on the server, you can do it regularly using the runtime.

// lib/env/server.ts

'use server';

const envSchema = z.object({
  PORT: z.coerce.number(),
});

export default envSchema.parse(process.env);
like image 98
brielov Avatar answered Sep 02 '25 16:09

brielov