alan2207/bulletproof-react · critical · Error
Invalid env provided. The following variables are missing or
Error message
Invalid env provided.
The following variables are missing or invalid:
${Object.entries(parsedEnv.error.flatten().fieldErrors)
.map(([k, v]) => `- ${k}: ${v}`)
.join('\n')}
What it means
Identical fail-fast pattern to the nextjs-app variant: createEnv() in apps/nextjs-pages/src/config/env.ts throws at module load when EnvSchema.safeParse() rejects the env vars (API_URL required, ENABLE_API_MOCKING must be the literal 'true'/'false'). Because `env` is computed at import time, any route/component importing the config crashes the Pages Router build or request before rendering.
Source
Thrown at apps/nextjs-pages/src/config/env.ts:26
.string()
.refine((s) => s === 'true' || s === 'false')
.transform((s) => s === 'true')
.optional(),
APP_URL: z.string().optional().default('http://localhost:3000'),
APP_MOCK_API_PORT: z.string().optional().default('8080'),
});
const envVars = {
API_URL: process.env.NEXT_PUBLIC_API_URL,
ENABLE_API_MOCKING: process.env.NEXT_PUBLIC_ENABLE_API_MOCKING,
APP_URL: process.env.NEXT_PUBLIC_URL,
APP_MOCK_API_PORT: process.env.NEXT_PUBLIC_MOCK_API_PORT,
};
const parsedEnv = EnvSchema.safeParse(envVars);
if (!parsedEnv.success) {
throw new Error(
`Invalid env provided.
The following variables are missing or invalid:
${Object.entries(parsedEnv.error.flatten().fieldErrors)
.map(([k, v]) => `- ${k}: ${v}`)
.join('\n')}
`,
);
}
return parsedEnv.data ?? {};
};
export const env = createEnv();
View on GitHub (pinned to 9506629ed0)
Solutions
- Create apps/nextjs-pages/.env.local with API_URL=http://localhost:3000 (plus NEXT_PUBLIC_ENABLE_API_MOCKING, NEXT_PUBLIC_APP_URL, NEXT_PUBLIC_MOCK_API_PORT as needed) and restart.
- Use the `- KEY: reason` lines in the thrown message to fix exactly the failing keys.
- For deployments: NEXT_PUBLIC_* vars must be present at build time — add them to your host's build environment, not just runtime.
- Loosen the schema (optional().default(...)) for variables that are legitimately absent in some environments.
Example fix
# before # apps/nextjs-pages/.env.local # (empty) # after API_URL=http://localhost:3000 NEXT_PUBLIC_API_URL=http://localhost:3000 NEXT_PUBLIC_ENABLE_API_MOCKING=false
Defensive patterns
Strategy: validation
Validate before calling
// Prebuild script (scripts/check-env.ts) run before `next build`
const required = ['API_URL'];
const missing = required.filter((k) => !process.env[k]);
if (missing.length) {
console.error(`Missing: ${missing.join(', ')}`);
process.exit(1);
} Type guard
import { z } from 'zod';
const EnvSchema = z.object({
API_URL: z.string(),
ENABLE_API_MOCKING: z.enum(['true', 'false']).optional(),
});
export const isEnv = (o: unknown): o is z.infer<typeof EnvSchema> =>
EnvSchema.safeParse(o).success; Try / catch
try {
const { env } = await import('@/config/env');
} catch (e) {
console.error((e as Error).message);
process.exit(1);
} Prevention
- Maintain per-app .env.local files — each app under apps/ has its own config root.
- Remember NEXT_PUBLIC_* vars are inlined at build time: set them in the build environment, not just runtime.
- Add an env check script to the prebuild phase in package.json.
- Use z.enum(['true','false']) for boolean-ish flags to get clearer errors than the refine() string.
When it happens
Trigger: Running `next dev`/`next build`/`next start` for apps/nextjs-pages without API_URL defined; setting ENABLE_API_MOCKING to '1', 'yes', or a boolean instead of 'true'/'false'; CI/preview environments lacking the NEXT_PUBLIC_* variables; SSR pages importing @/config/env during a build prerender pass with no env file present.
Common situations: Cloning the repo and only setting up apps/react-vite; deploying the pages app with env vars configured for the app-router app but not this one; Docker images built without baking in build-time NEXT_PUBLIC_ variables (which must exist at build time for client bundles).
Understand the failure class
Background: "environment variable is not set" and "Missing keys in environment" errors: what missing required env var messages mean and how to fix them — this error's family across 28 libraries.
Related errors
- Invalid env provided. The following variables are missing or
- Invalid env provided. The following variables are missing or
AI-assisted analysis of alan2207/bulletproof-react@9506629ed0 (2026-08-27).
Data as JSON: /api/errors/a1e71292741bc91e.
Report an issue: GitHub.