The word CORS stands for "Cross-Origin Resource Sharing". Cross-Origin Resource Sharing is an HTTP-header based mechanism implemented by the browser which allows a server or an API(Application Programming Interface) to indicate any origins (different in terms of protocol, hostname, or port) other than its origin from which the unknown origin gets permission to access and load resources. The cors package available in the npm registry is used to tackle CORS errors in a Node.js application.
Why Use CORS?
The reasons to use CORS in the application are
- Security: CORS helps to prevent malicious websites from accessing sensitive information on your server.
- Resource Sharing: It allows controlled access to resources on a server from a different origin, enabling web applications to make API requests to external services.
Let's understand using an example.
Steps to Implement/Enable CORS in Node App
Step 1: Check If Node is installed in your system
As the CORS package is available in npm(node package manager) that Node.js third-party package, we must have Node.js installed in our local system. To verify type the following command in the terminal.
node -v
The command will show the version of Node.js installed in your system. If it gives some error, make you install Node.js properly, for that follow this link.
Step 2: Project setup and folder structure. First, create a folder in your system named "geeksforgeeks" and move to the folder using a command prompt. Use the following command to do so.
mkdir geeksforgeeks && cd geeksforgeeks
Inside that folder create two separate folders: client and server(using same mkdir command). Inside the client, the folder creates index.html and script.js files. Inside the server folder type the following command to generate the package.json file :
npm init
Now, create an index.js file inside the server folder to write the server-side logic. Our current folder structure should look like this.
Project Structure: It will look like the following.

Step 3: Now inside the same directory, install necessary packages( express and cors) using the following command :
npm install express cors
The Updated dependencies in the package.json file:
"dependencies": { "cors": "^2.8.5", "express": "^4.19.2" }
Step 4: This is the code inside the index.html file. This is the main HTML code that will be shown to the client in the browser.
HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Sample webpage</title> <script src="script.js" defer></script> </head> <body> <h1>Sample Webpage</h1> <div id="data"></div> </body> </html> <!-- Frontend will be running on port 5500. -->
JavaScript document.addEventListener("DOMContentLoaded", () => { fetch('http://localhost:3000/api/data') .then(response => { if (!response.ok) { throw new Error('Network response was not ok ' + response.statusText); } return response.json(); }) .then(data => { document.getElementById('data').innerText = JSON.stringify(data, null, 2); }) .catch(error => { console.error('There has been a problem with your fetch operation:', error); }); });
We are allowing requests from some particular origins using the corsOptions object.
let corsOptions = { origin : ['http://localhost:5500'], } # this corsOptions object enables CORS action for all origins running on port 5500 only. # So if an application is running on any port other than 5000(own origin) and 5500, no CORS action will be enabled.
Inside the Server Directory:
Node // Filenamr index.js const express = require('express'); const cors = require('cors'); const app = express(); // CORS options to allow requests from frontend running on port 5500 const corsOptions = { origin: 'http://localhost:5500', // Allow only requests from this origin methods: 'GET,POST', // Allow only these methods allowedHeaders: ['Content-Type', 'Authorization'] // Allow only these headers }; // Use CORS middleware with specified options app.use(cors(corsOptions)); app.get('/api/data', (req, res) => { const responseData = { message: "Hello, GFG Learner", articleData: { articleName: "How to send JSON response from NodeJS", category: "NodeJS", status: "published" }, endingMessage: "Visit Geeksforgeeks.org for more" }; res.json(responseData); }); const port = 3000; app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); });
Steps to Run: Use the following command in server directory and server will start on the port 3000.
node index.js
Output:
Node js Cors ExampleConclusion
CORS is crucial for security and functioning of web applications making cross-origin requests. In Node.js, the cors
middleware for Express simplifies enabling and configuring CORS, allowing you to control resource sharing with fine-grained policies. This ensures that your API can be securely accessed by authorized web applications across different domains.
Similar Reads
Session Cookies in Node.js
HTTP protocol: It is the backbone of the internet every single request from the client for particular contains several HTTP headers and that contains all the information of the request. This protocol is the foundation of the data exchange over the internet but the HTTP protocol is the stateless prot
4 min read
Essence of Node.js
Node.js or Node has a small core group of modules, commonly referred to as the Node Core that is exposed as the public Node API by using we write our applications or we can say that the Node Core implements the public Node API. Some examples of the modules present in the node core are: To work with
8 min read
RESTful Routes in Node.js
Routing: Routing is one of the most significant parts of your website or web application. Routing in Express is basic, adaptable, and robust. Routing is the mechanism by which requests (as specified by a URL and HTTP method) are routed(directed) to the code that handles them. Â What is RESTful Routin
4 min read
HTTPS in Node.js
HTTP: When the data is transferred in HTTP protocol it just travels in the clear text format. HTTPS: It simply encrypts the request from the browser to the web server, so it is tough to sniff that information. It basically works on two things: SSL (Secure Socket Layer)TLS (Transport layer security
3 min read
HTTP Cookies in Node.js
Cookies are small data that are stored on a client side and sent to the client along with server requests. Cookies have various functionality, they can be used for maintaining sessions and adding user-specific features in your web app. For this, we will use cookie-parser module of npm which provides
4 min read
Express.js | router.use() Function
The router.use() function uses the specified middleware function or functions. It basically mounts middleware for the routes which are being served by the specific router. Syntax: router.use( path, function )Parameters: Path: It is the path to this middleware, if we can have /user, now this middlewa
2 min read
Express.js vs KoaJS in Node.js
Node.js: Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser. You need to remember that NodeJS is not a framework and itâs not a programming language. Most of the people are confused and understand itâs a framework or a programming languag
4 min read
Node.js DNS Complete Reference
Node.js DNS is a node module used to do name resolution facility which is provided by the operating system as well as used to do an actual DNS lookup. Example: [GFGTABS] JavaScript <script> // Node.js program to demonstrate the // dns.resolve() method // Accessing dns module const dns = requir
3 min read
HapiJS vs KoaJS in Node.js
HapiJS Module: In order to use the hapiJS module, we need to install the NPM (Node Package Manager) and the following modules (on cmd). // Create package.json file >> npm init // Installs hapi module >> npm install @hapi/hapi --save Import hapiJS module: Import hapiJS module and store re
3 min read
How to use SSL/TLS with Node.js ?
TLS/SSL is used for establishing secure connections over the internet. Today, most websites use HTTPS to communicate with clients. HTTPS is basically HTTP running over TLS/SSL. Web clients like browsers alert users about websites that do not use HTTPS since such websites are vulnerable to cyber-atta
5 min read