Topic 46 of 55
CORS
Overview
Browsers have a security feature called the Same-Origin Policy. It prevents a frontend (e.g., `http://localhost:3000`) from fetching data from an API on a different domain/port (e.g., `http://localhost:8080`). To allow this, the API must send CORS headers.
Syntax
javascript
// 1. Install the cors package
// npm install cors
const express = require('express');
const cors = require('cors');
const app = express();
// Simplest usage: Allows requests from ANY origin (Good for public APIs)
app.use(cors());
// Or, restrict it to specific origins for security:
const corsOptions = {
origin: 'https://my-frontend-website.com', // Only allow this domain
optionsSuccessStatus: 200 // Some legacy browsers choke on 204
};
app.use(cors(corsOptions));
app.get('/data', (req, res) => res.json({ secret: "data" }));Common Pitfalls
- CORS is enforced by the BROWSER, not the server. Postman or curl will bypass CORS entirely. It is not a security measure to prevent API abuse by bots.
- If `credentials: true` is set, you CANNOT use a wildcard `origin: '*'` due to browser security restrictions. You must specify the exact origins.
Real-World Example
Allowing multiple specific domains (e.g., development and production):
example
javascript
const whitelist = ['http://localhost:3000', 'https://myapp.com'];
const corsOptions = {
origin: function (origin, callback) {
// origin is undefined if the request is from a tool like Postman or curl
if (!origin || whitelist.indexOf(origin) !== -1) {
callback(null, true); // Allow
} else {
callback(new Error('Not allowed by CORS')); // Block
}
},
credentials: true // Crucial if you need to send cookies across origins
};
app.use(cors(corsOptions));