Sling Academy
Home/Node.js/How to Handle CORS in NestJS

How to Handle CORS in NestJS

Last updated: January 01, 2024

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.

Next Article: NestJS Circular Dependency Detected Error: How to Fix It

Previous Article: NestJS: How to Set Custom Status Code for Response

Series: Nest.js Tutorials: From Basics to Advanced

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates