Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
ReactJS CORS Options
Next article icon

NPM CORS

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Cross-Origin Resource Sharing (CORS) is a fundamental security mechanism implemented by web browsers to prevent unauthorized access to resources on a web page from different origins. In Node.js, CORS management is essential when building APIs that need to be consumed by clients running on different domains.

Table of Content

  • What is CORS?
  • Need for CORS in Node.js
  • Using npm Cors Package
  • Basic Usage
  • Features
  • Configuring CORS
  • Conclusion

What is CORS?

CORS is a security feature implemented by web browsers to restrict web pages from making requests to a different origin than the one from which the current page originated. This is enforced by the Same-Origin Policy, a security concept that restricts how documents or scripts loaded from one origin can interact with resources from another origin.

Need for CORS in Node.js

Node.js applications often serve APIs that need to be consumed by clients running on different origins. Enabling CORS in a Node.js server allows these clients to make requests to the server, even if they originate from different domains. This is crucial for building scalable and interoperable web applications.

Using npm Cors Package

The cors package is a popular middleware for Express.js that simplifies CORS configuration in Node.js applications. It provides a flexible way to configure CORS policies based on specific requirements, making it a go-to solution for managing cross-origin requests.

Installing npm Cors

To use cors in a Node.js project, developers need to install it via npm. They can do so by running the following command in the terminal:

npm install cors

Basic Usage

To use the cors module, you need to import it and apply it to your Express application. Here's a simple example of how to enable CORS for all requests in an Express-based application:

Node
// index.js
const express = require('express');
const cors = require('cors');

const app = express();

// Enable CORS for all routes
app.use(cors());

app.get('/', (req, res) => {
    res.send('CORS is enabled for all origins!');
});

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

Features

The cors module provides various features to configure cross-origin behavior in Node.js applications:

  • Origin Configuration: You can allow all origins or restrict access to specific origins. You can set a list of allowed origins or use a callback function to dynamically determine if a request is allowed.
  • HTTP Methods: The module lets you define which HTTP methods are allowed (e.g., GET, POST, PUT, DELETE).
  • HTTP Headers: You can specify which custom headers are allowed in CORS requests.
  • Credentials: If you need to support credentials like cookies or HTTP authentication, you can enable CORS with credentials.
  • Preflight Caching: The cors module can also help you handle preflight requests and set the caching duration for OPTIONS requests.

Configuring CORS

Allowing Specific Origins

If you want to restrict CORS to a specific origin, you can set it as follows:

const corsOptions = {
    // Allow only requests from this domain
    origin: 'http://example.com/',
};

app.use(cors(corsOptions));

Allowing Multiple Origins

You can also allow multiple origins by specifying them in an array:

const allowedOrigins = ['http://example.com/', 'http://ww25.another-domain.com/?subid1=20250723-2203-0668-a9d1-7f8effd1c8a9'];

const corsOptions = {
    origin: function (origin, callback) {
        if (allowedOrigins.indexOf(origin) !== -1 || !origin) {
            callback(null, true);
        } else {
            callback(new Error('Not allowed by CORS'));
        }
    },
};

app.use(cors(corsOptions));

Allowing Specific Methods

To allow only specific HTTP methods, use the following configuration:

const corsOptions = {
    // Only allow GET and POST requests
    methods: ['GET', 'POST'],
};

app.use(cors(corsOptions));

Supporting Credentials

If you need to support credentials, you can enable them with this configuration:

const corsOptions = {
    origin: 'http://example.com/',
    // Allow credentials like cookies
    credentials: true,
};

app.use(cors(corsOptions));

Customizing Headers

To specify which headers are allowed in CORS requests, use this approach:

const corsOptions = {
    // Allow specific headers
    allowedHeaders: ['Content-Type', 'Authorization'],
};

app.use(cors(corsOptions));

Conclusion

CORS management is crucial for securing Node.js applications and enabling cross-origin communication between clients and servers. The cors npm package simplifies CORS configuration in Node.js applications, allowing developers to define custom CORS policies and manage cross-origin resource sharing effectively. By understanding and implementing CORS correctly, developers can enhance the security and usability of their Node.js applications.


Next Article
ReactJS CORS Options

A

aayushkhosla16
Improve
Article Tags :
  • Web Technologies
  • Node.js
  • Node-npm

Similar Reads

    Python Falcon - CORS
    Cross-Origin Resource Sharing (CORS) is an additional security measure implemented by modern browsers to prevent unauthorized requests between different domains. When developing a web API with Falcon, it's common and recommended to implement a CORS policy to allow cross-origin requests securely. In
    4 min read
    Spring Security - CORS
    Cross-Origin Resource Sharing (CORS) is a security feature implemented by web browsers to allow or block web pages from making requests to a different domain than the one that served the web page. It plays a crucial role in preventing certain types of attacks, such as Cross-Site Request Forgery (CSR
    7 min read
    ReactJS CORS Options
    When building React apps, data is often fetched from external APIs or different domains. This can cause issues with CORS (Cross-Origin Resource Sharing), a security feature that prevents one domain from accessing resources on another without permission.How Does CORS Work? CORS enables secure communi
    6 min read
    JavaScript JSONP
    What is JSONP?The **XMLHttpRequest (XHR)** is a tool used to retrieve data from a server. Once the data is received by the browser, it can be converted from a JSON string into a JavaScript object using the `JSON.parse()` method. However, XHR encounters an issue known as the **same-origin policy**. T
    3 min read
    Use of CORS in Node.js
    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 th
    4 min read
    HTTP Access Control (CORS)
    Modern web applications often need to fetch data from different domains, known as a cross-origin request. For example, a site hosted on 'example.com' might need resources from 'api.example.com'. However, browsers enforce the Same-Origin Policy (SOP), which blocks requests to different domains for se
    7 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • DSA Tutorial
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences