You developed an API end point and this being used in frontend UI applications such as React,Angular and VueJS. API and UI apps are hosted on different domain, The communication between this two domains are not enabled by default.

To enable the communication and sharing the resources, CORS or Cross Origin Request Sharing should be enabled.

CORS must be enabled on Server side application to allow front end UI requests

How to enable CORS in Nest.JS

This framework provides enableCors method on NestJS application object.

Syntax:

enableCors([configurationobject]);

configurationobject is an optional object that contains below properties.

  • origin
  • methods
  • allowedHeaders
  • exposedHeaders
  • credentials
  • maxAge
  • preflightContinue
  • optionsSuccessStatus

Here is an example configuration object

{
  "origin": "*",
  "methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
  "preflightContinue": false,
  "optionsSuccessStatus": 204
}
const app = await NestFactory.create(AppModule);
app.enableCors({{
  "origin": "*",
  "methods": "GET,HEAD,PUT,PATCH,POST,DELETE"});
await app.listen(3000);

Enable CORS in Graphql NestJS application