What is CORS? : How to enable CORS in Nodejs App.

What is CORS? : How to enable CORS in Nodejs App.

·

4 min read

Cross-Origin Resource Sharing (CORS) is a web browser mechanism that allows for resources that are restricted outside a domain (origin) to be requested from another domain.

In this article, we'll get to understand why we use CORS and how to enable it in a Nodejs App.

Why do we use CORS?

To understand why we use CORS, we need to understand the underlying security risk it protects us from which is web scripting.

Web scripting is the process of creating and embedding scripts that automates various functions and sequential tasks in a web page. These scripts can be used for various purposes including animations, tracking of information within our application, integration, ads etc.

This variation poses a potential security risk because third-party scripts can access our application and steal sensitive data which can then be used to perform some harmful operations within our application. Due to this risk, same-origin policy was introduced.

Same-origin policy is a web mechanism that allows a web page to retrieve or access resources from applications that are within its origin. Two resources can be said to have the same origin if their URL has the same host, port, and protocol.

For instance:

https://www.hashnode.com and https://www.hashnode.com/@TonieNG are of the same origin while https://www.hashnode.com/@TonieNG and https://tonie.hashnode.dev/ are of different origins.

CORS serves as a mechanism that when enabled can allow for resource sharing between applications that are of different origins and it is implemented on top of HTTP so that the server side can instruct the browser to allow interactions from certain URLs.

It consists of a preflight request, sent by the browser before each request. A set of headers should then be added on every server response (preflight or not) to allow or disallow the request if the origin is forbidden.

How to enable CORS in Nodejs App?

  1. Create a new folder on your local device and open it with your preferred IDE. In this tutorial, I used VS Code.

  2. Open your terminal and type in the following code to initialize a nodejs project:

      npm init -y
    
  3. Now we need to install the dependencies for this project. Open your terminal and enter this command

      npm install cors dotenv express nodemon
    
  4. Create a file named index.js and in the package.json file add a start property within the script object. Your package.json and folder structure should look like this

  5. Next, go into the index.js file and type in the following to set up our application using express:

     const express = require("express");
     const app = express();
    
     app.get("/", (req, res) => {
       res.json({ name: "Tonie", role: "developer" });
     });
    
     app.listen(3000, () => {
       console.log(`Server is up and running`);
     });
    

    This is a simple nodejs application that returns a JSON object as its response.

  6. Now to enable CORS, we will need to make a few changes to our index.js file. Update the contents of your file to look like this

     const express = require("express");
     const cors = require("cors");
     const app = express();
    
     app.use(
       cors({
         origin: "http://127.0.0.1:example", //specify the receiving domain here
         methods: ["GET", "PUT", "POST", "DELETE"],
         credentials: true
       })
     );
    
     app.get("/", (req, res) => {
       res.json({ name: "Tonie", role: "developer" });
     });
    
     app.listen(3000, () => {
       console.log(`Server is up and running`);
     });
    

    As we can see, we are importing the cors module and calling it in our app. I'll explain the parameter listed there

    • origin: Here, we specify the domains or origins we want our application to communicate with. Any domain outside the one listed here will be blocked by the same-origin policy. To enable requests from any origin, we can use the wildcard "*" as the origin. ie origin: "*" .

    • methods: This is an array that contains the list of methods we allow in our application. If we do not provide the methods property, our application will accept all kinds of requests method.

    • credentials: This is a boolean value that allows our application to process things like cookies etc.

As we can see, it's quite easy to set up CORS in our Nodejs Application. For further clarifications or research, check the cors documentation. I've also provided the GitHub repository that contains the code written in this tutorial here (give it a star).

If you have any question or suggestions, feel free to ask in the comment section. You can also shoot me a DM on Twitter.

Happy Coding ✨

Did you find this article valuable?

Support Tonie by becoming a sponsor. Any amount is appreciated!