HttpOnly cookie is set only after the second request

Tags: , , ,



I have a server (Node.js + Nest.js) and a client (Angular 11).

The client submits a login request and the server logs in the user and sets a HttpOnly cookie in the response.
The wierd thing is that the cookie is set in the browser only after submitting 2 requests, then it works fine (If i use postman for example, it saves the cookie with no problems). I can see in each response (even the first one) the cookie set in the headers.

client code:

this.http.post<LoginResponse>(`server_path/login`, {
      email: 'example@gmail.com',
      password: '12345678',
      rememberMe: false
}).subscribe(_ => console.log('Logged in!'), _ => console.log('wrong credentials'))

server code:

const { result, error } = await this.authService.loginLocalUser(req.user, body.rememberMe)
if (error) throw new UnauthorizedException()

if (body.rememberMe) {
  const oneYearFromNow = new Date()
  oneYearFromNow.setFullYear(oneYearFromNow.getFullYear() + 1)
  res.cookie('refreshToken', result.refreshToken, { httpOnly: true, expires: oneYearFromNow })
} else
  res.cookie('refreshToken', result.refreshToken, { httpOnly: true })

return { accessToken: result.accessToken }

EDIT: even when the cookie is set (after the second time), I cant see it being sent in requests, even tho I use credentials: true on both client and server.

Answer

In the end the thing that solved my problem was just clearing the browser cache, no idea why its like that (only in chrome), but now everything is working as expected.



Source: stackoverflow