AI & Agent Dev Bug Sandbox logo
AI & Agent Dev Bug Sandbox
Back to Radar

Next/Jest Loads Server Runtime Into Jest Process Causing Process Listener Leak

next/jest transformer imports server runtime code that monkey-patches process event methods, causing test file process.on() calls to attach listeners to the real Jest process, leading to memory leaks across test files.

highConfidence 85%Next.jsAffected V16.3.4Affected V16.4.0-Canary.47

Origin Analysis

The transformer at next/dist/build/swc/jest-transformer.js requires build/swc/options.js, which transitively requires server/node-environment. That module's side effects replace process.on/addListener/etc with wrappers that always target the realm's original process instead of the caller's process object. Jest gives each test file its own process copy, so every listener added in a test file is bound to the real process and outlives the test environment.
1. Create a Next.js project with Jest configured via next/jest as per docs. 2. Write multiple test files that either start a custom Next server or simply call process.on('exit', () => {}). 3. Run jest and observe via a custom environment that the real process listener count grows with each test file, unlike plain Jest where it stays at zero.

Fixing Code Block

Edge Case Audit

This fix only addresses the listener binding issue but does not prevent the server runtime from being loaded into the Jest process, so other global side effects may remain. It may also affect any internal Next.js code that relies on the patched methods ignoring `this` and always targeting the realm's process. The change should be tested across Jest workers and concurrent test runs. Rollback is straightforward: revert the `.call(this, ...)` back to `.call(process, ...)`. A more complete fix would avoid importing server/node-environment in the transformer altogether.

Ecosystem Topology