diff --git a/lib/env.ts b/lib/env.ts index 8298fe52..1db2f190 100644 --- a/lib/env.ts +++ b/lib/env.ts @@ -1,9 +1,7 @@ -import './load-env'; import { z } from 'zod'; /** * Environment variable schema. - * This ensures the application has all required configuration at startup. */ const envSchema = z.object({ NODE_ENV: z.enum(['development', 'production', 'test']).default('development'), @@ -32,17 +30,14 @@ const envSchema = z.object({ MAIL_RECIPIENTS: z.string().optional().transform(val => val?.split(',').filter(Boolean) || []), }); -export type Env = z.infer; - /** * Helper to get environment variables. - * On the client, only NEXT_PUBLIC_ variables are available. - * On the server, all variables are available. */ function getRawEnv() { - if (typeof window !== 'undefined') { + const isServer = typeof window === 'undefined'; + + if (!isServer) { // Client-side: only return NEXT_PUBLIC_ variables - // We must explicitly reference them for Next.js inlining to work return { NEXT_PUBLIC_BASE_URL: process.env.NEXT_PUBLIC_BASE_URL, NEXT_PUBLIC_UMAMI_WEBSITE_ID: process.env.NEXT_PUBLIC_UMAMI_WEBSITE_ID, @@ -50,7 +45,7 @@ function getRawEnv() { }; } - // Server-side: return all variables from process.env + // Server-side: return all variables return { NODE_ENV: process.env.NODE_ENV, NEXT_PUBLIC_BASE_URL: process.env.NEXT_PUBLIC_BASE_URL, @@ -71,5 +66,11 @@ function getRawEnv() { /** * Validated environment variables. + * We use safeParse during build to avoid crashing the build process. */ -export const env = envSchema.parse(getRawEnv()); +const isBuildTime = process.env.NEXT_PHASE === 'phase-production-build'; +const parsed = isBuildTime + ? envSchema.safeParse(getRawEnv()) + : { success: true, data: envSchema.parse(getRawEnv()) }; + +export const env = parsed.success ? parsed.data : envSchema.parse({}); diff --git a/lib/load-env.ts b/lib/load-env.ts deleted file mode 100644 index 9be2e233..00000000 --- a/lib/load-env.ts +++ /dev/null @@ -1,10 +0,0 @@ -import dotenv from 'dotenv'; -import path from 'path'; - -/** - * Loads environment variables from .env file in development. - * This must be called before any other module that uses environment variables. - */ -if (typeof window === 'undefined' && process.env.NODE_ENV !== 'production') { - dotenv.config({ path: path.resolve(process.cwd(), '.env') }); -}