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:
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:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With