Using CORS in NestJs


cors nestjs Tutorials

Hello! If you are from Ukraine, Belarus, Poland or India and looking for a job in Software Development, please reach me out by email.

In this post, we will learn how to enable CORS in the NestJS application.

enableCors() method

You can enable CORS in your NestJS project by calling .enableCors() method of your app instance:

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();

If we make a request even in the browser we should face `Access-Control-Allow-Origin` header:

Enabled CORS in NestJS project

Without running this method the result will be another:

Disabled CORS in NestJs project

cors parameter

You can enable CORS in your NestJS project by passing an object as a second argument to .create function. Just set cors field value to true in this object:

async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    cors: true
  });
  // app.enableCors();
  await app.listen(3000);
}

Conclusion

You can see it is easy to configure CORS for your NestJS application. If you want flexible set-up just pass CORS object to .enableCors method or set it into cors parameter.

comments powered by Disqus