Henrique Ramos
Henrique Ramos

Reputation: 786

Why Nestjs not setting cookies in my browser?

I'm making an API in Nestjs that is consumed by an application in ReactJs. My problem is in the login route, when I use swagger, the cookie is saved in the browser normally but when I do a fetch from the front end, the cookie is not saved even though the response headers have the cookie.

I already tried to use all the sameSite options, I tried to put credentials include in the fetch but nothing works. If I log in to swagger first, then I try to do it in react, react copies the cookie that is saved in swagger.

For example, if in swagger I log in with user 1, and in react with the user 2, react steals the cookie from user 1 and ignores user 2 response cookie.

Code in react:

    const res = await fetch(`${API_URL}/auth/login`, {
      method: "POST",
      headers: { "Content-type": "application/json", accept: "*/*" },
      // credentials: "include",
      body: JSON.stringify(data),
    });

Main.ts:

    const corsOptions = {
    origin:
      process.env.NODE_ENV === 'development' ||
      process.env.MY_NODE_ENV === 'development'
        ? [process.env.PLATFORM_LOCAL_URL, process.env.LANDING_LOCAL_URL]
        : [process.env.PLATFORM_PROD_URL, process.env.LANDING_PROD_URL],
    credentials: true,
    allowedHeaders: 'Content-Type, Accept, Origin',
    preflightContinue: false,
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
  };

  app.enableCors(corsOptions);
  app.use(helmet());
  app.use(cookieParser());

Login Controller:

    @UseGuards(LocalAuthGuard)
  @Post('auth/login')
  async login(
    @Body() _: MakeAuthDto,
    @Request() req,
    @Res({ passthrough: true }) res,
  ) {
    const access_token = await this.authService.login(req.user);
    const cookiesOpts = {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'none',
      path: '/',
      maxAge: 60 * 60 * 24 * 3,
    };
    res.cookie('jwt', access_token, cookiesOpts);
    return {
      response: {
        user: req.user,
        expire: new Date().setDate(new Date().getDate() + 3),
      },
    };
  }

Work on swagger:

After call login route

After make request from ReactJs, the response cookies has the jwt: response cookies, reactjs

But the cookie are not stored:

cookie not stored

Upvotes: 4

Views: 6059

Answers (1)

ktretyak
ktretyak

Reputation: 31729

Looks like you're trying to set a cookie with the swagger editor.

See Note for Swagger UI and Swagger Editor users:

Cookie authentication is currently not supported for "try it out" requests due to browser security restrictions. See this issue for more information. SwaggerHub does not have this limitation.

Upvotes: 1

Related Questions