Sharing cookies/data from middleware to server-side props #38650
-
It seems like cookies modified in middleware aren’t visible to My specific use case: I’m trying to use middleware for refreshing auth tokens. I have a middleware that checks an accessToken stored in a cookie for expiration, and—if it’s nearing expiration—refreshes it and writes a new one as a cookie. However, data fetching that happens in Here’s a simplified test example that shows the problem: middleware.js: import { NextResponse } from 'next/server';
export function middleware(req) {
const res = NextResponse.next();
// 'test' cookie that lasts 10 seconds
const cookieSettings = { expires: new Date(Date.now() + 10 * 1000) };
req.cookies.set('test', 'value', cookieSettings);
res.cookies.set('test', 'value', cookieSettings);
return res;
} pages/index.jsx: export default function Home() { return null; }
export function getServerSideProps({ req }) {
console.log('Cookie from accessToken:', req.cookies.test);
return { props: {} };
} On the first request (where the middleware sets the cookie), I would expect that modifying the Is there another way to set cookies in middleware that makes the values visible to |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
Hi, The request is immutable, so it arrives to the Node.js server without changes, that's why your cookie is missing. What you can do is a bit of a magic trick... because you can read the response in export function getServerSideProps({ req, res }) {
console.log('Cookie from accessToken:', context.res.getHeader('set-cookie'));
return { props: {} };
} And from there you just have to parse that cookie, and possibly remove it or let it through. |
Beta Was this translation helpful? Give feedback.
-
I've run into this same problem and the other solution appears to be listed here: #31188. I wanted to raise this because I suspect many people have come across the same issue. |
Beta Was this translation helpful? Give feedback.
Hi,
The request is immutable, so it arrives to the Node.js server without changes, that's why your cookie is missing.
What you can do is a bit of a magic trick... because you can read the response in
getServerSideProps
, and from theregetHeader
, calledset-cookie
.And from there you just have to parse that cookie, and possibly remove it or let it through.