2

I'm generating JWT token on my Nestjs backend which then I try to send with cookie to my frontend React application in order to know which user is logged in.

Problem is that I'm not receiving this cookie in browser, and it's not automatically added to other requests.

I'm sending response inside my service like this:

async login(loginData: UserLoginInterface, res: Response) {

...

return res.status(200).cookie('jwt', token.accessToken, {
        secure: false,
        domain: 'localhost',
        httpOnly: false,
      }).json(userResponse);
}

At this point I know the token is generated, it's saved in DB.
But I can't see this cookie, or any other cookie I try in my browser: enter image description here

Doesn't matter if the httpOnly flag is true or false.

And then, when I try to call action that is restricted only for logged in user, which have the jwt token in request, then Nest is throwing 401 UnauthorizedException
So at this point I know that it's not sent automatically with request as I read in other thread like this:
Why browser is not setting the cookie sent from my node js backend?

But when I make this POST request from Postman.

Then I can see that cookie is sent properly and I can read the JWT token: enter image description here

Along with headers: enter image description here

And also it works fine when I call the function that is restricted only to authorized users.

Here is my bootstrap in main.ts:

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.enableCors({
    origin: 'http://localhost:3000'
  });

  app.getHttpAdapter().getInstance().disable('x-powered-by');

  app.use(cookieParser());

  await app.listen(process.env.PORT || 3500);
}
bootstrap();
BlackH3art
  • 436
  • 1
  • 7
  • 15

1 Answers1

1

After some time of debugging I found out that it's not the browser that is ignoring properly sent cookie, and in fact it is backend that is not sending the cookie to the browser client.
And the thing was about how the request is being send.

I've found this thread to be useful: Express doesn't set a cookie

In my case setting flag withCredentials: true in axios was sufficient.

const API = axios.create({ 
  baseURL: 'http://localhost:5000',
  withCredentials: true,
});

EDIT

Also, seems like the way I send response also matters, the code above is not sending cookie properly to the browser for some reason, but this works fine:

      res.status(200).cookie('jwt', token.accessToken);

      return res.json(userResponse);
BlackH3art
  • 436
  • 1
  • 7
  • 15