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

To enable the communication and sharing of 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 the enableCors method on the NestJS application object.

Syntax:

enableCors([configurationobject]);

configurationobject is an optional object that contains the 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