CORS

Cross-origin resource sharing (CORS) is a mechanism that allows resources to be requested from another domain. Under the hood, Nest makes use of the Express cors package. This package provides various options that you can customize based on your requirements.

Getting started

To enable CORS, call the enableCors() method on the Nest application object.

  1. const app = await NestFactory.create(AppModule);
  2. app.enableCors();
  3. await app.listen(3000);

The enableCors() method takes an optional configuration object argument. The available properties of this object are described in the official CORS documentation. Another way is to pass a callback function that lets you define the configuration object asynchronously based on the request (on the fly).

Alternatively, enable CORS via the create() method’s options object. Set the cors property to true to enable CORS with default settings. Or, pass a CORS configuration object or callback function as the cors property value to customize its behavior.

  1. const app = await NestFactory.create(AppModule, { cors: true });
  2. await app.listen(3000);

Above method only applies to REST endpoints.

To enable CORS in GraphQL, set cors property to true or pass CORS configuration object or a callback function as the cors property value when you import GraphQL module.

warning Warning CorsOptionsDelegate solution is not working with the apollo-server-fastify package yet.

  1. GraphQLModule.forRoot({
  2. cors: {
  3. origin: 'http://localhost:3000',
  4. credentials: true,
  5. },
  6. }),