Proposal: Standardize server-side cookie API across middleware, server actions, and API routes #82205
Replies: 1 comment
-
Hi @mattiamalonni, Thanks for sharing this proposal. I fully agree that having a unified server-side cookie API across middleware, server actions, API routes, and route handlers would be a big improvement. Currently, cookie handling differs between middleware (using NextRequest.cookies and NextResponse.cookies) and server actions or API routes (using cookies() from next/headers). This causes duplicated logic, extra branching, and confusion. Your example clearly shows that cookies set in middleware are not accessible later in server actions, which breaks the expected behavior. A standard, context-aware cookies() API that works the same way everywhere, detects the environment, and handles reading and writing properly would simplify development, reduce boilerplate, and make shared utilities like auth or sessions easier to implement. I look forward to this proposal progressing. Let me know if I can help test or give feedback. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Goals
Non-Goals
document.cookie
).Background
Next.js provides different APIs for cookie access depending on the execution environment:
NextRequest.cookies
andNextResponse.cookies
.cookies()
fromnext/headers
.This split introduces inconsistency and confusion for developers. Not only is the API surface different, but the behavior also diverges in subtle ways — especially when cookies are set in middleware and accessed downstream.
Example: Middleware sets a cookie, but server action can't read it
The reason: cookies() reads from the original incoming request, which hasn’t been modified by the middleware. This breaks the mental model that setting a cookie early in the lifecycle should make it available later.
Additional challenges:
• Shared utilities (e.g. for auth/session handling) must branch logic to check context?.nextRequest?.cookies vs. cookies().
• Middleware often requires duplicating logic to ensure cookies are set and read correctly.
• The discrepancy leads to boilerplate, fragile code, and developer confusion.
A unified approach would allow developers to reason about cookies in a consistent way across all server contexts.
Proposal
Introduce a standard, context-aware cookie API that works consistently across middleware, server actions, route handlers, and API routes.
Make
cookies()
universally availablecookies()
fromnext/headers
to be used in middleware as well.NextRequest
/NextResponse
in middleware).Such a change would greatly reduce duplication, clarify expectations, and offer a smoother developer experience for common tasks like authentication, sessions, flash messages, and experimentation.
Beta Was this translation helpful? Give feedback.
All reactions