next.js icon indicating copy to clipboard operation
next.js copied to clipboard

Race condition in action queue can undo navigation

Open dmitrc opened this issue 10 months ago β€’ 5 comments

Link to the code that reproduces this issue

https://github.com/dmitrc/nextjs-action-queue-race/blob/main/app/ReproButton.tsx

To Reproduce

  1. Start the app in dev mode and navigate to /
  2. Click on the button
  3. Observe the navigation to /other page
  4. Observe the unexpected undo to / page shortly

Here is the screen recording -- https://imgur.com/a/asaleSm.

Hopefully console logs I am attaching below explain the issue in more depth.

Current vs. Expected behavior

The app performs the following steps (exaggerated to be in one place for the demo purposes):

window.history.replaceState({}, "", url.toString());
callServerAction();
router.push("/other");
setTimeout(() => router.refresh(), 2_000);

Expected behavior is navigation to /other page, and for the refresh to happen in its context.

Current behavior is navigation to /other page, followed by unexpected redirect back to / shortly.

What happens here is a bit tricky to explain, but the following breakpoints help:

  • app-router-instance.ts:102 (action running)
  • app-router-instance.ts:108 (action resolved, but discarded)
  • app-router-instance.ts:122 (action resolved, applying new state)
  • app-router-instance.ts:174 (action being enqueued)

With those, here is what we see in the logs:

Image
  • restore gets enqueued and starts running (.pending)
  • server-action gets enqueued and put into .next
  • navigate gets enqueued, start running since hi-pri, and marks .pending to be discarded
  • restore finishes and gets discarded, runs server-action via runRemainingActions()
  • navigate finishes, sets the canonical URL in the state to /other
  • server-action finishes, ⚠️ sets the canonical URL in the state to /
    • This is the state that it started running with, but not up-to-date with latest navigation state
  • refresh gets enqueued, start running using latest canonical URL (which is /, wrongly)
  • RSC payload for / is delivered, page navigated back to / :(

Provide environment information

Operating System:
  Platform: linux
  Arch: x64
  Version: #1 SMP PREEMPT_DYNAMIC Thu Jun  5 18:30:46 UTC 2025
  Available memory (MB): 32019
  Available CPU cores: 32
Binaries:
  Node: 24.11.1
  npm: 11.6.2
  Yarn: 1.22.21
  pnpm: 9.15.4
Relevant Packages:
  next: 16.1.1-canary.19 // Latest available version is detected (16.1.1-canary.19).
  eslint-config-next: N/A
  react: 19.2.3
  react-dom: 19.2.3
  typescript: 5.9.3
Next.js Config:
  output: N/A

Which area(s) are affected? (Select all that apply)

Linking and Navigating

Which stage(s) are affected? (Select all that apply)

next dev (local), Other (Deployed), next start (local)

Additional context

No response

dmitrc avatar Jan 09 '26 19:01 dmitrc

Hi maintainers πŸ‘‹ I’d like to work on this issue. Please let me know if it’s already assigned to someone. Thanks!

hrishikesh2810 avatar Jan 12 '26 05:01 hrishikesh2810

@dmitrc Hi! I am a new contributor. I have created a PR #88550 for this issue. The details are in the description. At your convenience, please let me know if I need to make any improvements.

Thanks!

waqas2714 avatar Jan 14 '26 17:01 waqas2714

any updates?

Edit by maintainer bot: Comment was automatically minimized because it was considered unhelpful. (If you think this was by mistake, let us know). Please only comment if it adds context to the issue. If you want to express that you have the same problem, use the upvote πŸ‘ on the issue description or subscribe to the issue for updates. Thanks!

matteo2437 avatar Feb 03 '26 23:02 matteo2437

Navigation also bounces back for me. Happens consistently when I slow network speed to "slow 4G"

jeanmaried avatar Apr 22 '26 18:04 jeanmaried

We hit this same race in production (education SaaS, Next.js 16.2.6 stable) and independently root-caused it to the action queue before finding this issue. Posting our analysis since it adds a deterministic non-browser reproduction, a precise mechanism trace, and notes on the fix shape β€” we've been running a workaround in production via patch-package for the past week.

Mechanism (one level below the breakpoint trace in the description)

When a navigation supersedes an in-flight server action, dispatchAction marks the pending action discarded and starts the navigation immediately, inheriting the discarded action's queue tail. But in runAction (app-router-instance.ts), the discarded action's handleResult β€” and the rejection callback β€” still call runRemainingActions unconditionally when the action settles. At that moment the discarded action is not the queue head (the navigation is), so if it settles while the navigation's RSC fetch is still in flight, runRemainingActions advances actionQueue.pending past the running navigation and starts the next queued action with prevState = actionQueue.state β€” the pre-navigation state. (It also means two queue entries are now effectively running concurrently, and the navigation's own completion advances the queue a second time.)

When that stale-seeded action later resolves, every completion path in server-action-reducer propagates its captured state (the no-revalidation path literally return state), its handleResult writes actionQueue.state = <pre-navigation state>, and because its deferred promise is React's latest router-state promise, React commits the old canonicalUrl. The user silently "bounces back" to the previous page seconds after a successful navigation β€” no error, no redirect, no log. Retrying always works (a fresh navigation re-captures state), which makes it look random and unreportable.

Real-world impact

In our app every React Query fetch is a server action, so several are commonly in flight at page mount. Before we patched, analytics found 39 no-click A→B→A URL reverts in 14 days across users. The race window scales with server-action latency, which is consistent with the slow-4G repro reported above.

Deterministic reproduction (no browser)

This drives the queue logic copied verbatim from app-router-instance.js (16.1.6 β€” the relevant logic is unchanged in 16.2.6) with the timeline: slow action S1 in flight β†’ router.push navigation N (marks S1 discarded, inherits S2) β†’ S1 settles mid-navigation β†’ S2 starts with pre-navigation state β†’ N commits correctly β†’ S2 resolves and re-commits the pre-navigation canonicalUrl. Reproduces on every run:

t+ 927ms  [REACT COMMIT] canonicalUrl = /dashboard/classes/CLASS-X  (from N)
...
t+3608ms  [reducer] ACTION S4(any later query) STARTS β€” captured state.canonicalUrl = /dashboard/classes/my-classes   <-- POSTs to this URL
t+3912ms  [REACT COMMIT] canonicalUrl = /dashboard/classes/my-classes  (from S4(any later query))

*** BUG REPRODUCED: user navigated to CLASS-X but ended up back on my-classes ***
queue-race-sim.mjs β€” run with node queue-race-sim.mjs
// Deterministic simulation of the Next.js 16.1.6 action-queue race.
// dispatchAction / runAction / runRemainingActions are copied VERBATIM
// (modulo module plumbing) from
// node_modules/next/dist/client/components/app-router-instance.js.
// The reducer is a stub that mimics the timing behavior of
// navigateReducer / serverActionReducer: async, captures `state`, resolves later.

const ACTION_NAVIGATE = 'navigate'
const ACTION_RESTORE = 'restore'
const ACTION_SERVER_ACTION = 'server-action'

const log = []
const t0 = Date.now()
const now = () => `t+${String(Date.now() - t0).padStart(4)}ms`

// ---- verbatim queue logic (16.1.6) ----
function runRemainingActions(actionQueue, setState) {
  if (actionQueue.pending !== null) {
    actionQueue.pending = actionQueue.pending.next
    if (actionQueue.pending !== null) {
      runAction({ actionQueue, action: actionQueue.pending, setState })
    }
  } else {
    if (actionQueue.needsRefresh) {
      actionQueue.needsRefresh = false
      actionQueue.dispatch({ type: 'refresh' }, setState)
    }
  }
}

async function runAction({ actionQueue, action, setState }) {
  const prevState = actionQueue.state
  actionQueue.pending = action
  const payload = action.payload
  const actionResult = actionQueue.action(prevState, payload)
  function handleResult(nextState) {
    if (action.discarded) {
      if (action.payload.type === ACTION_SERVER_ACTION && action.payload.didRevalidate) {
        actionQueue.needsRefresh = true
      }
      runRemainingActions(actionQueue, setState)
      return
    }
    actionQueue.state = nextState
    runRemainingActions(actionQueue, setState)
    action.resolve(nextState)
  }
  if (typeof actionResult?.then === 'function') {
    actionResult.then(handleResult, (err) => {
      runRemainingActions(actionQueue, setState)
      action.reject(err)
    })
  } else {
    handleResult(actionResult)
  }
}

function dispatchAction(actionQueue, payload, setState) {
  let resolvers = { resolve: setState, reject: () => {} }
  if (payload.type !== ACTION_RESTORE) {
    const deferredPromise = new Promise((resolve, reject) => {
      resolvers = { resolve, reject }
    })
    // startTransition(() => setState(deferredPromise))  -- React side:
    setState(deferredPromise, payload.name)
  }
  const newAction = { payload, next: null, resolve: resolvers.resolve, reject: resolvers.reject }
  if (actionQueue.pending === null) {
    actionQueue.last = newAction
    runAction({ actionQueue, action: newAction, setState })
  } else if (payload.type === ACTION_NAVIGATE || payload.type === ACTION_RESTORE) {
    actionQueue.pending.discarded = true
    newAction.next = actionQueue.pending.next
    runAction({ actionQueue, action: newAction, setState })
  } else {
    if (actionQueue.last !== null) {
      actionQueue.last.next = newAction
    }
    actionQueue.last = newAction
  }
}

// ---- reducer stub mimicking real reducers' state capture + async timing ----
const sleep = (ms) => new Promise(r => setTimeout(r, ms))

function reducer(state, payload) {
  // mimics: serverActionReducer / navigateReducer capture `state` at start
  if (payload.type === ACTION_NAVIGATE) {
    return (async () => {
      await sleep(payload.fetchMs) // fetchServerResponse (RSC shell)
      log.push(`${now()}  [reducer] NAVIGATE ${payload.url} resolves (captured base=${state.canonicalUrl})`)
      return { canonicalUrl: payload.url, tree: payload.url }
    })()
  }
  if (payload.type === ACTION_SERVER_ACTION) {
    return (async () => {
      log.push(`${now()}  [reducer] ACTION ${payload.name} STARTS β€” captured state.canonicalUrl = ${state.canonicalUrl}   <-- POSTs to this URL`)
      await sleep(payload.fetchMs)
      log.push(`${now()}  [reducer] ACTION ${payload.name} resolves`)
      if (payload.didRevalidate) {
        // server-action-reducer.js:264-301 β€” navigate to captured canonicalUrl
        return { canonicalUrl: state.canonicalUrl, tree: state.tree, via: `navigate-after-${payload.name}` }
      }
      // bail-out (line 240-247): "return state" β€” the CAPTURED state object
      return state
    })()
  }
  if (payload.type === 'refresh') {
    return (async () => {
      await sleep(50)
      return { ...state, via: 'refresh' }
    })()
  }
}

// ---- React side: latest dispatched promise wins (useState semantics) ----
let latestPromise = null
let committed = { canonicalUrl: '/dashboard/classes/my-classes', tree: 'my-classes' }
function setState(p, name) {
  latestPromise = p
  const mine = p
  Promise.resolve(p).then((s) => {
    if (latestPromise === mine) {
      committed = s
      log.push(`${now()}  [REACT COMMIT] canonicalUrl = ${s.canonicalUrl}  (from ${name ?? 'action'}${s.via ? ', via ' + s.via : ''})  ==> HistoryUpdater pushes/replaces URL`)
    }
  })
}

const actionQueue = {
  state: { canonicalUrl: '/dashboard/classes/my-classes', tree: 'my-classes' },
  dispatch: (payload, ss) => dispatchAction(actionQueue, payload, ss),
  action: (state, payload) => reducer(state, payload),
  pending: null,
  last: null,
  needsRefresh: false,
}

// ---- Repro timeline ----
// t=0     my-classes page mounts; two React Query server-action queries fire
dispatchAction(actionQueue, { type: ACTION_SERVER_ACTION, name: 'S1(getPageSettings)', fetchMs: 400 }, setState)
dispatchAction(actionQueue, { type: ACTION_SERVER_ACTION, name: 'S2(slow query, heavy account)', fetchMs: 3000 }, setState)

// t=200   user clicks a class card -> router.push(class detail)
setTimeout(() => {
  log.push(`${now()}  [user] clicks class card -> NAVIGATE /dashboard/classes/CLASS-X`)
  dispatchAction(actionQueue, { type: ACTION_NAVIGATE, name: 'N', url: '/dashboard/classes/CLASS-X', fetchMs: 700 }, setState)
}, 200)

// t=1500  user clicks the Attendance tab -> enables tracker query (another server action)
setTimeout(() => {
  log.push(`${now()}  [user] clicks Attendance tab -> useOptimizedTrackerAttendance fires`)
  dispatchAction(actionQueue, { type: ACTION_SERVER_ACTION, name: 'S3(attendance tracker)', fetchMs: 800 }, setState)
}, 1500)

// t=3600  any later server-action query fires (custom statuses, realtime-debounce
// invalidation refetch, stats, etc.) β€” AFTER the stale S2 wrote back
setTimeout(() => {
  log.push(`${now()}  [app] another query fires -> S4`)
  dispatchAction(actionQueue, { type: ACTION_SERVER_ACTION, name: 'S4(any later query)', fetchMs: 300 }, setState)
}, 3600)

setTimeout(() => {
  log.push(`${now()}  FINAL committed canonicalUrl: ${committed.canonicalUrl}`)
  log.push(`${now()}  FINAL actionQueue.state.canonicalUrl: ${actionQueue.state.canonicalUrl}`)
  console.log(log.join('\n'))
  if (committed.canonicalUrl === '/dashboard/classes/my-classes') {
    console.log('\n*** BUG REPRODUCED: user navigated to CLASS-X but ended up back on my-classes ***')
  } else {
    console.log('\n(no bounce in this run)')
  }
}, 5000)

On the fix shape

The invariant that seems to matter: a settled action should only advance the queue if it is still the queue head. The workaround we run in production (patch-package on 16.2.6) replaces the unconditional runRemainingActions in (a) the action.discarded branch of handleResult and (b) the rejection callback with:

if (actionQueue.pending === action) {
  runRemainingActions(actionQueue, setState)
} else if (actionQueue.pending === null && actionQueue.needsRefresh) {
  actionQueue.needsRefresh = false
  actionQueue.dispatch({ type: ACTION_REFRESH }, setState)
}

A discarded action is never the head (the navigation replaced it), so the guard is exact, and the intended "discarded revalidating action triggers a refresh once the queue drains" behavior is preserved.

For comparison with the approach in #88550 (skip applying the result when actionQueue.state !== prevState): that prevents the stale commit, but the stale-seeded action still starts while the navigation is in flight β€” so it captures pre-navigation state and its server-action POST is issued against the pre-navigation canonicalUrl, and the discarded branch still advances the queue past the running navigation. Guarding at the queue-head level means queued actions don't start until the navigation settles, so they capture post-navigation state and POST to the correct URL.

Happy to provide more detail or test candidate fixes against our production workload.

EMStudioPro avatar Jul 10 '26 09:07 EMStudioPro

We hit a complementary manifestation of this queue race in production on Next.js 16.2.6: the App Router suspends forever instead of navigating back.

The minimal dispatch sequence is:

  1. A client navigation is pending (N1, with pending === last === N1).
  2. A second client navigation (N2) preempts it.
  3. A Server Action (or router.refresh()) is dispatched before N2 settles.

In the navigation-preemption branch, N2.next inherits N1.next and runAction makes N2 pending, but actionQueue.last is not updated:

actionQueue.pending.discarded = true
newAction.next = actionQueue.pending.next
runAction({ actionQueue, action: newAction, setState })

When N1 had no tail, last still points to discarded N1. The later Server Action is therefore appended to N1.next, while the live queue drains through N2.next (which is null). The action is unreachable and never runs. Its dispatch already passed a deferred promise to React's router state, so useActionQueue remains suspended on a promise that can never resolve. The browser keeps painting the previous UI indefinitely; only a full-document reload recovers.

This is distinct from, and complementary to, guarding runRemainingActions so a discarded action cannot advance a replacement navigation. That guard prevents stale actions from advancing the live queue, but the empty-tail preemption case still needs to make the replacement navigation the tail, for example:

newAction.next = actionQueue.pending.next
if (newAction.next === null) {
  actionQueue.last = newAction
}
runAction({ actionQueue, action: newAction, setState })

Our application-level trigger was two post-auth navigations (push from a form plus replace from an auth guard), followed by a first-login locale Server Action. Removing the duplicate navigation fixes the race; we also use a delayed window.location.replace watchdog rather than retrying through the App Router.

mydaogs avatar Jul 16 '26 08:07 mydaogs