guest@mukunda.com:/blog# ./cat 2023/nestjs-and-cors.txt Name: Using CORS headers with NestJS Date: July 2, 2023 Happy weekend everyone. I've been writing a project with the NestJS Framework recently. If you've come across this article, you've probably already bumped into a handful of other articles that tell you how to "enable cors", but really nothing useful on how to set options for each endpoint. I mean really, who would actually want to enable a single set of CORS options for their entire site? Here is an example of using guards to decorate a method with CORS headers: @Injectable() class AllowCorsGuard implements CanActivate { constructor(private readonly reflector: Reflector) {} async canActivate( context: ExecutionContext, ): Promise<boolean> { const req = context.switchToHttp().getRequest() as Request; const res = context.switchToHttp().getResponse() as Response; const allowedOrigins = this.reflector.get('allowedCrossOrigins', context.getHandler()) as string[]|undefined; const origin = req.header("origin"); if (allowedOrigins && allowedOrigins.includes(origin)) { res.setHeader('Access-Control-Allow-Origin', origin); } return true } } export function AllowCors(...origins: string[]) { return applyDecorators( UseGuards(AllowCorsGuard), SetMetadata('allowedCrossOrigins', origins), ); } Usage: // Allow from example.com origin. @AllowCors("https://example.com") @Get() async get() { return "Hello World"; } Enjoy! Send the author a comment << Index