Delete httpOnly cookies - Express

Viewed 2353

Is it possible to delete browser cookies that are set as HttpOnly:true?

My login endpoint is simple like this:

  async login(@Ip() ipAddress, @Request() req, @Res() res: Response) {
      const auth = await this.basicAuthService.login(req.user, ipAddress);
      const cookieOptions = setTokenCookie();
      res.cookie('token', auth.token,  { httpOnly: true, expires: myDate()});
      res.cookie('refreshToken', auth.refreshToken, { httpOnly: true, expires: myDate()});
      res.send(auth);
    }

Works perfect, I call the /login endpoint in my react front end with axios

const res = await axios.post(`${baseUrl}/authentication/login`, { email, password }, { withCredentials: true });

So far, so good, cookies are set. But I want to delete those cookies when I log out, since they are HttpOnly:true I can't delete them on frontend. I have tried with res.clearCookie() method but they are still in the browser.

  async logout(@Request() req, @Res() res: Response) {
      res.clearCookie('refreshToken' ,{ domain: 'localhost', path: '/', expires: new Date(0) });
      res.clearCookie('token', { domain: 'localhost', path: '/', expires: new Date(0) });
      console.log('cookies deleted');
      res.send();
    }

I thought this wasn't possible and then, I tried to login in my Facebook account and I was able to see some HttpOnly:true cookies which are deleted when logout.

1 Answers

I know this question is almost 2 years old but was the first link I found when trying to fix the same issue.

From the Express 4.x - API Reference

Web browsers and other compliant clients will only clear the cookie if the given options is identical to those given to res.cookie(), excluding expires and maxAge.

To properly delete an httpOnly cookie you must pass that as an option in the second parameter as such

res.clearCookie('token', { httpOnly: true });

I believe the same applies to sameSite, secure etc

Related