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

Next.Js Build Intermittently Fails With E696 Invariant: Expected WorkUnitAsyncStorage To Have A Store During Static Export Under Load

During `next build` static export on large apps, a race condition in Next.js 16.1.6 (and canary) causes random pages to fail with `Invariant: Expected workUnitAsyncStorage to have a store` (E696). The issue occurs only under heavy CPU load, making it hard to reproduce in CI. Root cause is context loss from `workUnitAsyncStorage` when `getFlightResponse` is first touched outside the `workUnitAsyncStorage.run` scope via abort-path unwind or backpressure resume.

highConfidence 85%Next.jsAffected V16.1.6

Origin Analysis

Race condition in `server/app-render/use-flight-response.js`: `getFlightResponse` memoizes the deserialized flight response per stream at first touch and reads `workUnitAsyncStorage.getStore()` from whatever async context makes that first touch. If that first touch occurs outside any `workUnitAsyncStorage.run(store, …)` scope (due to abort handler execution in the enclosing scope or backpressure resume from the consumer's `pull()`), the store is `undefined`, triggering the E696 invariant. The store is only functionally needed for `prerender-client` deferral; the throw is a context-loss tripwire.
1. Clone repro: `https://github.com/discordwell/next-e696-workunit-store-race` 2. Run `npm install` 3. Run `npm run repro` (loops `next build --webpack` under CPU spinners; set `RUNS=25` for more attempts) 4. Observe intermittent failure: `Error [InvariantError]: Invariant: Expected workUnitAsyncStorage to have a store. This is a bug in Next.js.` on random static pages during `Generating static pages` phase. Requires genuine machine-wide CPU contention.

Fixing Code Block

Edge Case Audit

This is a homegrown patch not yet validated by the Next.js core team. It may mask other context-loss bugs if the store is genuinely required for other operations. Test thoroughly under load, including with `prerender-client` and `validation-client` features. If the build still fails or produces incorrect HTML, revert by removing these modifications and use the `experimental.staticGenerationRetryCount: 3` workaround until an official fix is released. Upgrading to a future Next.js version without this issue is the long-term solution.

Ecosystem Topology