Deleting a Cookie from Middleware
Answered
North Pacific hake posted this in #help-forum
North Pacific hakeOP
Deletion doesnt work from middleware,
const res = NextResponse.redirect(req.nextUrl);
res.cookies?.delete('session');
return res;Answered by North Pacific hake
const res = NextResponse.redirect(req.nextUrl);
res.cookies?.set({ name:"jwt.refresh", maxAge: 0 });
return res;but you have to check if the
jwt.refresh cookie exists else it will loop infinitely.Complete Solution:
const refreshCookie = cookies().get("jwt.refresh")?.value;
if (refreshCookie && tokenExpired) {
const res = NextResponse.redirect(req.nextUrl);
res.cookies?.set({ ...jwtRefreshCookie, maxAge: 0 });
return res;
}11 Replies
@North Pacific hake check out this
https://nextjs.org/docs/app/api-reference/functions/cookies#cookiesdeletename
https://nextjs.org/docs/app/api-reference/functions/cookies#cookiesdeletename
@North Pacific hake solved?
North Pacific hakeOP
Solved but using other trick
Cookies() dont work in middleware
Cookies() dont work in middleware
why don't you share your solution?
@North Pacific hake Solved but using other trick
Cookies() dont work in middleware
yea, please share your solution
@North Pacific hake would you mind sharing your solution?
North Pacific hakeOP
const res = NextResponse.redirect(req.nextUrl);
res.cookies?.set({ name:"jwt.refresh", maxAge: 0 });
return res;but you have to check if the
jwt.refresh cookie exists else it will loop infinitely.Complete Solution:
const refreshCookie = cookies().get("jwt.refresh")?.value;
if (refreshCookie && tokenExpired) {
const res = NextResponse.redirect(req.nextUrl);
res.cookies?.set({ ...jwtRefreshCookie, maxAge: 0 });
return res;
}Answer
@North Pacific hake
const res = NextResponse.redirect(req.nextUrl);
res.cookies?.set({ name:"jwt.refresh", maxAge: 0 });
return res;
but you have to check if the `jwt.refresh` cookie exists else it will loop infinitely.
Complete Solution:
const refreshCookie = cookies().get("jwt.refresh")?.value;
if (refreshCookie && tokenExpired) {
const res = NextResponse.redirect(req.nextUrl);
res.cookies?.set({ ...jwtRefreshCookie, maxAge: 0 });
return res;
}
I thought
But you are using
Cookies() dont work in middleware(https://nextjs-forum.com/post/1264606816512381069#message-1265672879329247312)
But you are using
const refreshCookie = cookies().get("jwt.refresh")?.value;
North Pacific hakeOP
It works while getting but not while setting/deleting
Apologies for the delay, the bot was irresponsive. Now it is fixed, the answer has been marked