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:
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:
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();