Introduction
When developing web applications, you may encounter a CORS error while connecting a frontend application to a Node.js backend. For example, your React or Angular application may send a request to an Express API, but the browser blocks access to the response.
This problem often occurs when the frontend and backend run on different origins. An origin consists of the protocol, hostname, and port. For example, http://localhost:3000 and http://localhost:5000 are different origins because they use different ports.
CORS (Cross-Origin Resource Sharing) is a browser security mechanism that controls whether a web page can access resources from another origin. If your Node.js server does not return the appropriate CORS headers, the browser may block the frontend from reading the API response.
In this tutorial, you will learn what CORS is, why CORS errors occur in Node.js, how to fix them in Express, and how to configure CORS securely for real-world applications.
What Is CORS in Node.js?
CORS stands for Cross-Origin Resource Sharing. It is a browser-enforced security mechanism based on HTTP response headers.
Browsers use the same-origin policy to restrict certain cross-origin requests made by web pages. CORS allows a server to specify which origins are permitted to access its responses.
For example, imagine you have the following applications:
- Frontend: http://localhost:3000
- Node.js API: http://localhost:5000
When the frontend sends a request to the backend, the browser checks whether the server permits the frontend’s origin.
If the server returns an appropriate header, such as:
Access-Control-Allow-Origin: http://localhost:3000
the browser can allow the frontend JavaScript to access the response, subject to the request and other CORS rules.
If the required CORS headers are missing or incorrect, the browser may display a CORS error in the developer console.
Important: CORS is enforced by browsers. A request made through a backend service, command-line tool, or Postman is not blocked by the browser’s CORS enforcement in the same way.
Why Do CORS Errors Occur in Node.js?
CORS errors commonly occur when a frontend application requests data from a backend that has not been configured to permit the frontend’s origin.
Common causes include:
- Different origins: The frontend and backend use different protocols, hostnames, or ports.
- Missing CORS headers: The Node.js server does not return the required Access-Control-Allow-Origin header.
- Incorrect origin configuration: The server allows one origin, but the frontend uses another.
- Failed preflight requests: The server does not correctly respond to an OPTIONS request sent by the browser.
- Credentials configuration: Cookies or other credentials are used without the appropriate CORS settings.
- Middleware ordering: CORS middleware is registered after routes or other middleware that prevents the required headers from being returned.
Understanding the cause makes it easier to apply the correct solution.
Example of a CORS Error
Suppose your React application sends a request to a Node.js API.
Frontend code:
fetch("http://localhost:5000/api/users")
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error(error));
Your Express server returns user data but does not configure CORS:
const express = require("express");
const app = express();
app.get("/api/users", (req, res) => {
res.json([
{ id: 1, name: "Amit" },
{ id: 2, name: "Priya" }
]);
});
app.listen(5000, () => {
console.log("Server running on port 5000");
});
If the frontend runs on http://localhost:3000, the browser may block the frontend JavaScript from reading the API response because the server has not permitted that origin.
The browser console may display a message similar to:
Access to fetch at ‘http://localhost:5000/api/users’
from origin ‘http://localhost:3000’ has been blocked
by CORS policy.
The exact message depends on the request and the browser.
How to Fix a CORS Error in Node.js
The easiest way to configure CORS in an Express application is to use the cors middleware.
1. Install the CORS Package
Open a terminal in your Node.js project’s root directory and run:
npm install cors
This installs the package needed to configure CORS headers in Express.
2. Enable CORS in Express
Import the cors package and register its middleware before your API routes.
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors());
app.get("/api/users", (req, res) => {
res.json([
{ id: 1, name: "Amit" },
{ id: 2, name: "Priya" }
]);
});
app.listen(5000, () => {
console.log("Server running on port 5000");
});
In this example, app.use(cors()) enables CORS for all origins by default for the configured routes and supported requests.
Restart the Node.js server and try the frontend request again.
Security note: Allowing all origins may be acceptable for a public API that intentionally provides public data. For private APIs, it is better to configure a specific allowlist of trusted origins.
Configure CORS for a Specific Origin
In production applications, you should generally allow only the frontend origins that need access to your API.
For example, suppose your frontend is hosted at https://www.example.com.
You can configure Express as follows:
const express = require("express");
const cors = require("cors");
const app = express();
const corsOptions = {
origin: "https://www.example.com"
};
app.use(cors(corsOptions));
app.get("/api/users", (req, res) => {
res.json({
message: "CORS configured successfully",
users: [
{ id: 1, name: "Amit" },
{ id: 2, name: "Priya" }
]
});
});
app.listen(5000, () => {
console.log("Server running on port 5000");
});
This configuration allows browser requests from https://www.example.com.
If the frontend is running at a different origin, such as http://localhost:3000, that origin will not be allowed by this configuration.
For local development, you can explicitly allow both development and production origins:
const allowedOrigins = [
"http://localhost:3000",
"http://localhost:4200",
"https://www.example.com"
];
app.use(cors({
origin: allowedOrigins
}));
Use the actual origins for your project. Do not include URL paths in origin values.
Handling CORS Preflight Requests
Some cross-origin requests trigger a browser preflight request. Before sending the actual request, the browser sends an OPTIONS request to check whether the server permits the intended method and headers.
Preflight requests are common when an application uses methods such as PUT or DELETE, or sends certain custom headers or content types.
For example, a frontend might send a request like this:
fetch("http://localhost:5000/api/users/1", {
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "Amit Sharma"
})
});
Configure the Express server to handle the request:
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors({
origin: "http://localhost:3000",
methods: ["GET", "POST", "PUT", "DELETE"],
allowedHeaders: ["Content-Type", "Authorization"]
}));
app.use(express.json());
app.put("/api/users/:id", (req, res) => {
res.json({
message: "User updated successfully",
id: req.params.id,
user: req.body
});
});
app.listen(5000, () => {
console.log("Server running on port 5000");
});
The cors middleware can handle preflight requests for the configured routes when registered application-wide as shown above.
It specifies the allowed origin, methods, and request headers. If a preflight request fails, the browser generally does not send the actual request.
Handling CORS with Cookies and Credentials
Some applications use cookies for login sessions. In such cases, the frontend may need to send credentials with cross-origin requests.
Frontend example:
fetch("http://localhost:5000/api/profile", {
method: "GET",
credentials: "include"
})
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error(error));
The Express server must allow the frontend’s specific origin and credentials:
app.use(cors({
origin: "http://localhost:3000",
credentials: true
}));
When credentialed requests are used, the server cannot use Access-Control-Allow-Origin: *. It must return a specific allowed origin.
Also, CORS configuration alone does not guarantee that cookies will be sent. Cookie attributes such as SameSite and Secure, browser privacy rules, and the application’s authentication setup must also be configured correctly.
Real-Life Example: Connecting a React Frontend to Node.js
Consider a project with the following setup:
- React frontend: http://localhost:3000
- Node.js backend: http://localhost:5000
- API endpoint: /api/products
The Express server can be configured like this:
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors({
origin: "http://localhost:3000",
methods: ["GET", "POST"],
allowedHeaders: ["Content-Type", "Authorization"]
}));
app.use(express.json());
const products = [
{ id: 1, name: "Laptop", price: 50000 },
{ id: 2, name: "Keyboard", price: 1500 }
];
app.get("/api/products", (req, res) => {
res.json(products);
});
app.listen(5000, () => {
console.log("API running on port 5000");
});
The React component can retrieve the products:
import { useEffect, useState } from "react";
function Products() {
const [products, setProducts] = useState([]);
const [error, setError] = useState("");
useEffect(() => {
fetch("http://localhost:5000/api/products")
.then((response) => {
if (!response.ok) {
throw new Error("Failed to load products");
}
return response.json();
})
.then(setProducts)
.catch((error) => setError(error.message));
}, []);
if (error) {
return {error}
;
}
return (
{products.map((product) => (
-
{product.name} - ₹{product.price}
))}
);
}
export default Products;
When both applications are running and the server permits the frontend origin, the browser can allow the React application to read the product data.
If the request still fails, inspect the browser’s Network and Console tabs. The problem might be an incorrect API URL, a server error, a failed preflight request, or a network issue rather than CORS alone.
How to Debug CORS Errors in Node.js
Follow these steps when a CORS error appears in the browser.
1. Check the Frontend Origin
Confirm the exact origin of the frontend, including its protocol, hostname, and port.
For example, these are different origins:
- http://localhost:3000
- http://localhost:4200
- https://localhost:3000
2. Check the Network Tab
Open browser developer tools and select the Network tab. Inspect the API request and any preceding OPTIONS request.
Check the response headers for Access-Control-Allow-Origin and, where relevant, the allowed methods, headers, and credentials settings.
3. Check Middleware Order
Register CORS middleware before routes that need CORS headers.
app.use(cors());
app.use("/api", apiRoutes);
If a route or other middleware sends a response before CORS middleware runs, the expected headers may be missing.
4. Verify the Backend Response
Confirm that the Node.js server is running and that the API URL is correct.
A 404 Not Found, 500 Internal Server Error, or connection failure may be the underlying problem. CORS headers must also be present on relevant error responses when the browser needs to read them.
5. Avoid Disabling Browser Security
Do not disable browser security features as a permanent fix. Configure the server to return the correct CORS headers instead.
Common CORS Mistakes in Node.js
1. Allowing the Wrong Origin
An origin must match the frontend’s protocol, hostname, and port. Check for differences such as http versus https or localhost:3000 versus localhost:4200.
2. Using a Wildcard with Credentials
This configuration is invalid for credentialed browser requests:
app.use(cors({
origin: "*",
credentials: true
}));
Use a specific allowed origin when credentials are required.
3. Forgetting Preflight Requests
Some requests require a successful OPTIONS preflight response. Make sure your CORS middleware and server configuration allow the requested methods and headers.
4. Adding CORS Headers Only to Successful Responses
If error responses do not include the necessary CORS headers, the browser may prevent frontend JavaScript from reading those responses. Registering suitable CORS middleware early in the Express pipeline can help.
5. Treating CORS as Authentication
CORS is not a replacement for authentication or authorization. Non-browser clients can still send requests to your API. Protect private endpoints using proper authentication, authorization, and input validation.
Best Practices for CORS in Node.js
- Use the cors middleware for Express applications.
- Allow only trusted origins when working with private APIs.
- Register CORS middleware before the routes that require it.
- Configure allowed methods and headers according to actual application needs.
- Use a specific origin when sending cookies or other credentials.
- Inspect browser Network and Console tabs to identify the actual failure.
- Keep authentication and authorization separate from CORS configuration.
- Avoid disabling browser security to work around CORS errors.
- Use environment-specific origins for development, staging, and production.
Conclusion
CORS errors in Node.js commonly occur when a browser frontend tries to access an API without receiving the required cross-origin permissions. These errors can usually be resolved by configuring the Express server with the correct CORS headers and allowing the intended frontend origin.
The cors middleware makes this configuration straightforward. For production applications, use a trusted-origin allowlist, handle preflight requests correctly, and configure credentials carefully.
Understanding CORS helps developers connect React, Angular, and other frontend applications to Node.js APIs while maintaining appropriate browser security.