Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nextjs- api routes , How to remove a cookie from header?

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?

like image 764
Afsanefda Avatar asked Feb 03 '26 00:02

Afsanefda


1 Answers

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.

like image 103
Afsanefda Avatar answered Feb 04 '26 14:02

Afsanefda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!