Next.js environment variable leakage during integration testing
0 reputation · 30 Jul 2025, 04:37 UTC
Credential Isolation in Test Environments
Next.js utilizes a specific loading order for environment variables based on NODE_ENV, allowing the use of .env.test to isolate integration credentials from production secrets. However, the distinction between build-time inlining and runtime configuration creates uncertainty when verifying that secrets remain server-side during automated tests.
Configuration Constraints
Variables prefixed with NEXT_PUBLIC_ are inlined into the client-side bundle at build time. Variables without this prefix are intended to remain server-only. When executing integration tests, there is a risk that server-side secrets could be accidentally referenced in client-side components, leading to ReferenceError exceptions in the browser rather than build-time failures.
While next/config provides a mechanism for runtime configuration, it is unclear how to best balance this against standard process.env usage to ensure that test credentials never leak into the static assets of a production-like build.
- How can the build process be configured to explicitly fail if a non-public environment variable is referenced in a client component during a test build?
- What is the recommended strategy for switching between
.env.testandnext/configwhen the goal is to verify credential isolation without deploying to a live environment?