Stale cookie value when set in middleware
Unanswered
jxn posted this in #help-forum
jxnOP
Hi!
Noticed that if one sets a cookie value in middleware then it is not updated in the same request further down in pages and server component.
Tried to make a minimal repro with the following:
root
Logs I am getting refreshing the page 2 times
You can see initial
Am I missing something here? Is it possible to set a cookie value in middleware and read it in the same request in server components? Thanks!
Noticed that if one sets a cookie value in middleware then it is not updated in the same request further down in pages and server component.
Tried to make a minimal repro with the following:
middleware.js:import { NextResponse } from 'next/server';
export function middleware(request) {
console.log('--------');
console.log('initial', request.cookies.get('test')?.value);
const value = new Date().valueOf();
console.log('middleware', value);
request.cookies.set('test', value);
const response = NextResponse.next();
response.cookies.set('test', value);
return response;
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};root
page.jsx:import { cookies } from 'next/headers';
export default function () {
const value = cookies().get('test')?.value;
console.log('page', value);
return <div />;
}Logs I am getting refreshing the page 2 times
initial 1698448854995
middleware 1698448860030
page 1698448854995
--------
initial 1698448860030
middleware 1698448862946
page 1698448860030You can see initial
cookies().get() and in the page values basically lag 1 page update behindAm I missing something here? Is it possible to set a cookie value in middleware and read it in the same request in server components? Thanks!
3 Replies
Why are you setting cookies twice in your middleware?
jxnOP
it is setting it once for the incoming request on the server updating the value to be used futher down in the request and once for the outgoing response for the browser as a Set-Cookie header to be updated on the client as well
jxnOP
anyways
created an issue in the nextjs repo to follow https://github.com/vercel/next.js/issues/57655
seems reasonable to me
created an issue in the nextjs repo to follow https://github.com/vercel/next.js/issues/57655
seems reasonable to me