Using CORS in NestJs


cors nestjs Tutorials

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