CORS (Cross-Origin Resource Sharing) is a browser security feature that restricts web pages from making requests to a different domain (origin) than the one that served the web page.
- Origin = protocol + domain + port
- If your frontend is
http://localhost:3000and your backend ishttp://localhost:5000, the browser considers it cross-origin.
🔹 Why CORS Happens
- Browsers block cross-origin requests by default for security.
- Backend must explicitly allow certain origins, methods, or headers.
Symptoms:
Access to fetch at 'http://localhost:5000/api' from origin 'http://localhost:3000' has been blocked by CORS policy
🔹 Handling CORS in Node.js (Express.js)
1. Using cors package (recommended)
npm install cors
const express = require("express");
const cors = require("cors");
const app = express();
// Enable CORS for all origins
app.use(cors());
// Or restrict to specific origin
// app.use(cors({ origin: "http://localhost:3000" }));
app.get("/api/data", (req, res) => {
res.json({ message: "CORS enabled!" });
});
app.listen(5000, () => console.log("Server running on port 5000"));
- Automatically sets appropriate headers:
Access-Control-Allow-OriginAccess-Control-Allow-MethodsAccess-Control-Allow-Headers
2. Manual Header Setup (without package)
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "http://localhost:3000");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
res.header("Access-Control-Allow-Headers", "Content-Type, Authorization");
next();
});
🔹 CORS Preflight Request
- For some requests (PUT, DELETE, custom headers), the browser sends an OPTIONS request first (preflight).
- The server must respond with allowed methods/headers.
corspackage automatically handles preflight requests.
✅ Key Points
- CORS is browser-enforced, not server-enforced.
- Always allow only trusted origins in production.
- Use
corsmiddleware in Express.js for simple handling. - Preflight requests (OPTIONS) must be handled for complex requests.