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

Cookies() Inside After() Returns Pre-Mutation Values In A Route Handler

In Route Handlers, calling cookies() inside after() returns the inbound cookie snapshot instead of the mutated values because the mutable cookie jar is not synchronized before after() switches the work unit phase.

highConfidence 89%Next.jsAffected V16.4.0-Canary.15

Origin Analysis

after() changes workUnitStore.phase to 'after', causing cookies() to fall back to the immutable inbound snapshot. Route Handlers have no call to synchronizeMutableCookies before this phase flip, so mutations made in the handler are not propagated to the snapshot.
Create a Route Handler that reads cookies(), sets session=NEW, reads cookies() again (inHandler=NEW), then calls after() and reads cookies() inside the callback. Send a request with Cookie: session=OLD. Observe response body has inHandler=NEW and Set-Cookie: session=NEW, but inside after() the read returns OLD.

Fixing Code Block

Edge Case Audit

This patch may double-sync in Server Actions where synchronizeMutableCookies is already called in action-handler.ts, though the function is expected to be idempotent. If an official fix later changes the call site, this patch may conflict; rollback by removing the added import and call and restoring the original phase handling. Note that the cookie state is captured at after() registration time; any mutations performed after after() is called but before the callback executes will not be reflected.

Ecosystem Topology