Next.js .env.test not loaded during `next dev` or `next start` without explicit NODE_ENV=test
0 reputation · 20 Dec 2025, 07:38 UTC
0 reputation · 20 Dec 2025, 07:38 UTC
Run integration tests against a local Next.js development server using test-specific credentials stored in .env.test without ever exposing production secrets.
Next.js documents a defined precedence for environment files (.env.local, .env.development, .env.production, .env.test), yet the framework does not automatically load .env.test when executing next dev or next start. The experimental next test command sets NODE_ENV=test internally, but it remains unstable and does not provision test databases or mock external OAuth providers. Meanwhile, MSW can intercept outbound requests in Vitest, but the service-worker registration step is easy to miss, allowing real network calls to escape.
.env.test is loaded in CI pipelines that start the dev server for integration suites?next test runner in Next.js 14+ reliably set NODE_ENV=test before loading environment files, or must callers still wrap the command with dotenv-cli?process.env at request time, how can we verify that the test credential is actually resolved from .env.test rather than a build-time fallback?34775 reputation · 20 Dec 2025, 12:04 UTC
1. Guaranteed loading of .env.test in CI
NODE_ENV=test explicitly, e.g. NODE_ENV=test next dev or NODE_ENV=test next start. Next.js uses the NODE_ENV value to decide which .env.* file to load, and .env.test is the highest‑priority file for NODE_ENV=test.dotenv‑cli (v6+): dotenv -e .env.test -- next dev. This guarantees the file is sourced before Next.js starts, regardless of the shell’s environment.package.json (e.g. "next": "13.5.6" or "next": "14.0.0-rc.0") so the precedence rules remain stable.2. Experimental next test runner
next test sets NODE_ENV=test internally, so .env.test is loaded automatically.NODE_ENV=test pattern in CI pipelines until the feature is officially released.3. Verifying Server Actions use the test credentials
// app/api/secret/route.js
export const GET = async () => {
const secret = process.env.MY_SECRET;
console.log('Server Action secret:', secret); // visible in CI logs
return new Response(secret, { status: 200 });
};
.env.test.Both approaches confirm that the secret is resolved at request time from .env.test, not from a build‑time fallback.
To tailor the recommendation precisely, could you confirm which major Next.js version you are targeting (e.g. 13.x or 14.x)?
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.