To enable Cross-Origin Resource Sharing (CORS) in a Node.js application

Example 1 : To enable CORS in single route

app.get("/api/records", function(req, res) {
    res.append("Access-Control-Allow-Origin", "*");
    res.append("Access-Control-Allow-Methods", "*");
    res.append("Access-Control-Allow-Headers", "*");

Example 2 : To enable CORS in all route

app.use(function(req, res, next) {
    res.append("Access-Control-Allow-Origin", "*");
    res.append("Access-Control-Allow-Methods", "*");
    res.append("Access-Control-Allow-Headers", "*");

Example 3 : To enable CORS with package

Install the "cors" package:

First, you need to install the "cors" package:

npm install cors

Set up CORS in your Node.js application:

In your Node.js application (e.g., with Express.js), use the "cors" middleware to enable CORS for your routes. Here's an example:

const express = require('express');
const cors = require('cors');
const app = express();
const port = 3000;

// Enable CORS for all routes (for any origin)

// Define your API routes or middleware here
app.get('/api/data', (req, res) => {
  // Your API logic here
  res.json({ message: 'This is an example API response.' });

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

In the example above, the app.use(cors()) line enables CORS for all routes and allows requests from any origin. You can further customize the CORS settings by passing options to the cors function.

Customize CORS Options:

You can customize CORS options to control which origins, HTTP methods, and headers are allowed. For example, to allow requests only from a specific origin:

const corsOptions = {
  origin: '', // Replace with the desired origin


You can also allow multiple origins by using an array:

const corsOptions = {
  origin: ['', ''],


Additionally, you can specify other CORS options, such as allowed HTTP methods, allowed headers, and more, based on your application's requirements.

By setting up CORS in your Node.js application, you can control which domains are allowed to access your server's resources, thereby enhancing security while enabling cross-origin functionality for legitimate use cases.

Why we need CORS in Node.js?

Cross-Origin Resource Sharing (CORS) is used in Node.js and web applications to control how web resources on one domain can be accessed by web pages from another domain. It's essential for various reasons:

Security: CORS is a security feature implemented by web browsers to enforce the same-origin policy. The same-origin policy prevents web pages from making requests to domains other than the one that served the web page. This is crucial for protecting sensitive data and resources on your server.

Cross-Domain API Requests: When you have a Node.js API or server that needs to be accessed by web applications hosted on different domains, you must use CORS to explicitly specify which domains are allowed to access your API. This is especially important when building single-page applications (SPAs) or serving APIs to third-party clients.

Web Security: Enabling CORS allows you to define which origins (domains) are permitted to access your resources. This ensures that only trusted domains can access your API or server, reducing the risk of unauthorized access and data breaches.

Client-Side Requests: Modern web applications often rely on client-side code, such as JavaScript, to make requests to APIs. CORS ensures that these client-side requests adhere to the same-origin policy while allowing exceptions for trusted domains.

Cross-Origin Cookies: Without proper CORS configuration, web browsers may block cookies and authentication tokens from being sent with cross-origin requests. CORS headers allow you to control cookie behavior.

Cross-Domain Authentication: When using authentication mechanisms like OAuth or token-based authentication, CORS plays a significant role in allowing the client application to request access tokens from the authorization server.

Third-Party Integrations: If you want to integrate your Node.js application with third-party services or APIs, CORS is necessary to establish a secure and controlled connection to these external resources.

Access Control: CORS allows you to define fine-grained access control rules, such as which HTTP methods (e.g., GET, POST, PUT) are allowed for specific endpoints.

CORS in Node.js is used to ensure secure communication between your server and web clients while respecting the same-origin policy. It allows you to specify which origins are allowed to access your resources, thereby preventing unauthorized access and protecting your server's data. Properly configuring CORS is crucial for both security and enabling legitimate cross-origin functionality in web applications.

aung thu oo



Ko Aung Thu Oo

Having over 15 years of working experience in Laravel, PHP, Flutter, Node.Js, Vue.JS, JAVA. Strong information technology professional with a degree i...

View detail