How to Handle CORS in NestJS

Updated: January 1, 2024 By: Guest Contributor Post a comment

Introduction

Dealing with Cross-Origin Resource Sharing (CORS) is essential when building web applications with a front-end and back-end separated. In this tutorial, we will explore how to handle CORS in NestJS using TypeScript, ensuring your API is accessible in a secure and controlled manner.

Enabling CORS Globally

By default, NestJS does not enable CORS, due to security reasons; however, it can be configured easily. You can enable CORS for all routes in your NestJS application with a single option when initializing the main application module.

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableCors();
  await app.listen(3000);
}
bootstrap();

This will enable CORS with default settings, which means that any domain can make requests to your application.

Configuring CORS Options

If you need finer control over CORS configuration, you can pass options to `enableCors()`.

app.enableCors({
  origin: 'http://example.com',
  methods: 'GET,POST',
  allowedHeaders: 'Content-Type,Accept',
});

This example restricts CORS requests to those originating from ‘http://example.com’ and limits the methods and headers the client can use.

Using Middleware for Fine-Grained Control

Sometimes you need more dynamic control over CORS. For this, NestJS allows middleware configurations. Here’s how you can use Express’s `cors` package.

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as cors from 'cors';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.use(cors({ origin: 'http://example.com' }));
  await app.listen(3000);
}
bootstrap();

Javascript’s dynamic nature allows you to easily configure CORS according to your application logic.

Route-Specific CORS

NestJS also offers the ability to enable or configure CORS for specific routes, allowing more fine-tuned control.

import { Controller, Get, Req, UseGuards } from '@nestjs/common';
import { Request } from 'express';
import { Cors } from '@nestjs/common';

@Controller('cats')
export class CatsController {
  @Get()
  @Cors({ origin: 'http://example.com' })
  findAll(@Req() request: Request): string {
    return 'This action returns all cats';
  }
}

Note that the `Cors()` decorator is used here to enable CORS on a specific route only.

Dynamic CORS Configuration

Dynamic configuration comes in handy when the CORS policy needs to vary based on the incoming request. Here’s a charity wink to express your route.”

This action retrieves your requestanford.Network trafficBSTOL.Tel.’Based on For startup financing.

This acrual también organization:

Doubted in size with parallels.

app.enableCors({
  origin: function (origin, callback) {
    const allowedOrigins = ['http://example1.com', 'http://example2.com'];
    if (allowedOrigins.indexOf(origin) !== -1) {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));
    }
  },
});

Conclusion

To summarize, implementing and managing CORS in NestJS is a straightforward process, whether you require basic global settings or more granular configurations for specific endpoints or dynamic conditions. By following the steps and examples provided, you can ensure that your NestJS-powered applications communicate securely and efficiently with clients across different origins.