I have two API routes which I want to set two cookies in /api/login.js and remove them in /api/logout.js.
so this is my login API:
import { serialize } from 'cookie';
export default async (req, res) => {
res.setHeader('Set-Cookie', [
serialize('mytoken1', 'mytoken1Value', {
path: '/',
}),
serialize('mytoken2', 'mytoken2Value', {
path: '/',
}),
]);
res.writeHead(302, { Location: '/' });
res.end();
}
and this is my logout API:
export default async (req, res) => {
res.removeHeader('Set-Cookie')
res.writeHead(302, { Location: '/api/login' });
res.end();
}
but the logout doesn't remove the cookies so I still can see them in _app.js ---console.log(req.headers.cookie)--- when I reload the page. Do you know how to remove a cookie in this situation?
So, after challenging too much with every solution I ended up with this and it works fine:
(I had multiple cookies and I had to use nodejs methods cause I was coding in nextjs API routes without any middleware)
export default async (req, res) => {
/* remove cookies from request header */
res.setHeader('Set-Cookie', [
serialize('mytoken1', '', {
maxAge: -1,
path: '/',
}),
serialize('mytoken2', '', {
maxAge: -1,
path: '/',
}),
]);
res.writeHead(302, { Location: '/api/login' });
res.end();
}
The point was the maxAge which should be -1 to make it expire. I tried it with Date.now(). And when you have multiple cookies you have to end the response after manipulating both of them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With