admin管理员组

文章数量:1204972

I’m encountering a problem with CORS and cookies in my application deployed on Vercel (frontend) and Render (backend). Locally, everything works perfectly, but when deployed, the backend doesn’t seem to be receiving cookies from the frontend when trying to access getSessionInfo method.

Setup: Frontend: Next app hosted on Vercel (). Backend: NestJS API hosted on Render ().

I noticed that when i do sign in, it sends cookies with query and returns a 200 status code with all the necessary data. But then when i need to get session, it doesn't send cookies and thus i get 401 error. Both queries are client-side.

Backend bootstrap function

async function bootstrap() {
   const PORT = process.env.PORT!
   const app = await NestFactory.create(AppModule)

   const allowedOrigins = [
      "http://localhost:3000",
      "http://localhost:5000",
      ";,
      ";,
   ]

   app.use(cookieParser())

   app.enableCors({
      origin: (origin, callback) => {
         if (!origin) return callback(null, true)

         if (allowedOrigins.includes(origin)) {
            callback(null, true)
         } else {
            callback(new Error(`Origin "${origin}" not allowed by CORS`));
         }
      },
      methods: "GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS",
      credentials: true,
   })

   const config = new DocumentBuilder()
      .setTitle("Title")
      .build()

   const document = SwaggerModule.createDocument(app, config)
   SwaggerModule.setup("/", app, document)

   await app.listen(PORT)
}
bootstrap()

getSessionInfo

@Get("session")
   @UseGuards(AuthGuard)
   @ApiOkResponse({ type: GetSessionInfoDto })
   getSessionInfo(@SessionInfo() session: GetSessionInfoDto) {
      return session
   }

signIn

@Post("sign-in")
   @ApiOkResponse()
   @HttpCode(HttpStatus.OK)
   async signIn(@Body() body: SignInDto, @Res({ passthrough: true }) res: Response) {
      const { accessToken } = await this.authService.signIn(body.login, body.password)
      this.cookieService.setToken(res, accessToken)
   }

cookie.service.ts

@Injectable()
export class CookieService {
   static tokenKey = "access-token"

   setToken(res: Response, token: string) {
      res.cookie(CookieService.tokenKey, token, {
         httpOnly: true,
         expires: new Date(Date.now() + 24 * 60 * 60 * 1000),
         sameSite: "none",
         secure: true,
      })
   }

   removeToken(res: Response) {
      res.clearCookie(CookieService.tokenKey)
   }
}

AuthGuard

@Injectable()
export class AuthGuard implements CanActivate {
   constructor(private jwtService: JwtService) {}

   async canActivate(context: ExecutionContext) {
      const req = context.switchToHttp().getRequest() as Request;
      const token = req.cookies && req.cookies[CookieService.tokenKey];

      if (!token) {
         throw new UnauthorizedException();
      }

      try {
         const sessionInfo = await this.jwtService.verifyAsync(token, {
           secret: process.env.JWT_SECRET || 'secret_key', 
         });

         req['session'] = sessionInfo;
      } catch (error) {
          console.error("JWT verification error:", error);
          throw new UnauthorizedException();
      }

      return true;
   }
}

SessionInfo decorator

export const SessionInfo = createParamDecorator(
   (_, ctx: ExecutionContext) => ctx.switchToHttp().getRequest().session,
)

本文标签: nodejsCORS and Cookies not working on deployed NextNestJS application (VercelRender)Stack Overflow