How To Use CORS in NestJS Application

In this post, we will talk about how to use CORS (Cross-Origin Resource Sharing) in a NestJS application. Before showing, how easy it is to enable CORS, we will cover some fundamentals in this post.

  • What is CORS?
  • What is the NestJS framework?
  • How to use CORS?

What is CORS?

In a usual REST API-based application, there is a client that calls the API served by a Server. When accessing these APIs, clients can request different resources, and this includes images, videos, iframes, or scripts. A website requesting resources can be on a different domain compared to the domain of the resource. By default, a request to fetch resources can fail. That’s when CORS comes into the picture.

As said previously, CORS stands for Cross-Origin Resource Sharing. By default, CORS makes a call from client to server more secure. In many cases, we are aware of who the client is and what domain it is going to be on. In such cases, we want to relax the security for clients calling the APIs. We do this by the client sending request headers Access-Control-Allow-Origin. These headers indicate which origins can access the API.

CORS is an HTTP-header-based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources. – Mozilla Firefox

Let’s look at the following diagram

CORS in NestJS Application

A client from the abccompany.com sends a request to s3.amazon.com to access a resource from S3. In this case, the client and server have different origins. Usually, this request will fail because of cross-origins. It’s a security concern for browsers. CORS allows to access a resource from a server with a different origin compared to a request originating from. CORS will add Access-Control-Allow-Origin headers in the request.

What is NestJS Framework?

NestJS is a framework to build scalable NodeJS server-side applications. In the background, NestJS uses HTTP server frameworks like Express.

To get started,

npm i -g @nestjs/cli

Nest provides an out-of-the-box application architecture which allows developers and teams to create highly testable, scalable, loosely coupled, and easily maintainable applications – NestJS

Create a new project with Nest

nest new project-name.

How to use CORS?

To show how to use CORS, we will create a nestjs application.

nest new corsdemoapp – will create a new folder for corsdemoapp.

Now if I run npm start, it will start our default nestjs application at http://localhost:3000.

NestJs makes this really easier by providing a method enableCors().  This will look like below:

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableCors();
  await app.listen(3000);
}
bootstrap();

There is another way to enable CORS. By passing cors as an object in NestFactory.create() method.

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

If we want to see the response headers for the request made to http://localhost:3000 , they will look like below:

CORS NestJS Application without Headers

NestJS Application CORS Headers

The second screenshot shows the header Access-Control-Allow-Origin with the value of *. That means requests from any origin source can access the server to get response from http://localhost:3000.

What are the other options we can add for CORS?

There are a few other options that we can set with CORS while enabling through enableCors(). If we know, what other domains will be accessing our API, we can set that domain. Sometimes, the API can be public. In that case, we can use the wild card * for Access-Control-Allow-Origin.

app.enableCors(
    { 
      origin: ['https://betterjavacode.com', 'https://www.google.com'],
    }
  );

Also, we can only allow a set of methods for API calls.

app.enableCors(
    { 
      origin: ['https://betterjavacode.com', 'https://www.google.com'],
      methods: ['POST', 'PUT', 'DELETE', 'GET']
    }
  );

The most common use case of CORS is when building RESTful APIS in the backend and calling them through the frontend.

Conclusion

When building and deploying applications on servers, it is important to know who is calling your APIs. CORS provides a security feature. Accepting a request from every domain can pose a security risk. NestJS provides a simple way to enable CORS and options to add domains from which the server can accept the request. CORS allows us to avoid cross-site request forgery attacks (CSRF). I cover some of the common exploits in my book Simplifying Spring Security.