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

History.PushState Reverts When Prefetched Link And Proxy.Ts Cookie-Based Redirect Coexist

In Next.js 16.1.7, calling history.pushState to update a URL query parameter on a route containing a prefetched <Link> to the same dynamic segment may immediately revert to the previous URL. The regression occurs when a proxy.ts middleware redirects to restore a cookie-stored parameter, and a useEffect writes that parameter to a cookie. The router's prefetch cache fuzzy-matches the old entry and dispatches a restore action, undoing the user's navigation.

highConfidence 85%Next.jsAffected V16.1.7

Origin Analysis

Next.js monkey-patches history.pushState and, during a client-side pushState, dispatches an ACTION_RESTORE that consults the router prefetch cache. Prefetched <Link> entries keyed by the original URL (e.g., /?view=a&period=7d) are present. When pushState changes to /?view=a&period=90d, the cache lookup fuzzy-matches the old prefetched entry and restores its URL, triggering the proxy.ts redirect that reads the cookie set by the previous useEffect, reinforcing the revert. The combination of prefetch cache, cookie persistence, and middleware redirect creates a feedback loop.
1. Clone https://github.com/asanoop24/nextjs-pushstate-prefetch-revert-repro, install dependencies, build, and start. 2. Open http://localhost:3000. 3. Click any period button (e.g., 7d) to seed the last-period cookie. 4. Click a different period button (e.g., 90d). 5. Observe the URL briefly updates to ?period=90d then immediately reverts to ?period=7d; the RSC tree remains for the old URL.

Fixing Code Block

Edge Case Audit

This workaround disables prefetching for the affected links, which may slightly increase navigation latency and reduce performance. It does not address the underlying router cache bug; if the application adds other prefetched links to the same route or uses router prefetching, the issue may reappear. Before deploying, verify that the URL no longer reverts under all navigation paths. To rollback, remove prefetch={false} and upgrade to a Next.js version that contains the official fix. Also ensure that the proxy.ts redirect does not cause infinite loops; monitor server logs.

Ecosystem Topology