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
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
How to Separate Routers and Controllers in Node.js ? In a Node.js application, especially when using the Express framework, separating routers and controllers is a common practice to keep the codebase organized, maintainable, and scalable. This separation of concerns ensures that routing logic is kept separate from the business logic, making the appli
4 min read
Node.js DNS Node.js DNS (Domain Name System) module provides methods for performing DNS lookups and working with domain names. It allows you to resolve domain names into IP addresses and vice versa, which is essential for network communications and server management.DNS Module in Node.jsThe DNS module in Node.j
3 min read
How to Manage Users in Socket.io in Node.js ? Socket.IO is a library that enables real-time, bidirectional, and event-based communication between the browser and the server. Managing users in Socket.io and Node.js typically involves handling user connections, disconnections, and broadcasting messages to specific users or groups of usersPrerequi
9 min read