Middleware cannot access cookies set in server actions.
The issue involves cookies set in server actions not being accessible in middleware responses. The problem is reproducible but requires understanding of both server actions and middleware cookie handling. The scope is somewhat clear but involves cross-cutting concerns between different Next.js features.
https://github.com/marcospassos/next-middleware-cookie-bug
If you set a cookie in a server action, it is not available in the middleware. Without this, the middleware cannot prevent overriding cookies that may be set at the request time.
Create a server action:
'use server';
import {cookies} from 'next/headers';
export async function example(): Promise<void> {
cookies().set('foo', 'bar');
}
Then, in your middleware:
export function middleware(): void {
const response = NextResponse.next();
console.log(response.cookies.has('foo'));
}
The result is always false.
The response should include the cookies set in server actions.
Operating System:
Platform: darwin
Arch: arm64
Version: Darwin Kernel Version 23.4.0: Fri Mar 15 00:12:25 PDT 2024; root:xnu-10063.101.17~1/RELEASE_ARM64_T6030
Available memory (MB): 18432
Available CPU cores: 11
Binaries:
Node: 21.7.3
npm: 10.5.0
Yarn: N/A
pnpm: N/A
Relevant Packages:
next: 14.2.3 // Latest available version is detected (14.2.3).
eslint-config-next: 14.0.3
react: 18.3.1
react-dom: 18.3.1
typescript: 5.4.5
Next.js Config:
output: N/A
Middleware
next dev (local)
No response
Claim this issue to let others know you're working on it. You'll earn 20 points when you complete it!