Express.js CORS
CORS stands for Cross-Origin Resource Sharing. It is a browser security rule that controls which websites may call an API from another address. A frontend running at one address often needs data from an Express API running at a different address. The browser blocks that call unless the API says it is allowed. Express handles this with a few lines of setup.
What Is an Origin
An origin combines three parts: the protocol, the domain, and the port. Two addresses share an origin only when all three parts match.
| Frontend Address | API Address | Same Origin |
|---|---|---|
| http://localhost:3000 | http://localhost:3000 | Yes |
| http://localhost:3000 | http://localhost:5000 | No, port differs |
| https://shop.com | https://api.shop.com | No, domain differs |
| http://shop.com | https://shop.com | No, protocol differs |
The Building Guard Analogy
A building guard holds a list of approved visitors. A visitor from an unlisted company stands outside until someone adds the name. The browser acts as the guard, and the API holds the list. The API tells the browser which origins may enter by sending special response headers.
CORS Flow Diagram
Frontend (localhost:3000)
|
| GET /api/products
v
Express API (localhost:5000)
|
| Response with header:
| Access-Control-Allow-Origin: http://localhost:3000
v
Browser checks the header
|
Match found -> data reaches the frontend
No match -> browser blocks the data
Preflight Requests
Some requests trigger an extra check called a preflight. The browser sends an OPTIONS request first and asks the API whether the real request is allowed. Requests with methods like PUT or DELETE, or with custom headers such as Authorization, start this check. The API replies with the allowed methods and headers. The browser sends the real request only after a positive reply.
Browser --OPTIONS /api/items--> API Browser <--allowed methods---- API Browser --DELETE /api/items/5-> API
Install the cors Package
npm install corsAllow Every Origin
The simplest setup opens the API to all websites. Use it for public data only.
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.get('/api/products', (req, res) => {
res.json([{ id: 1, name: 'Laptop' }]);
});
app.listen(5000);Allow Specific Origins
Production apps list the trusted sites by name. Every other site stays blocked.
const allowedOrigins = [
'https://myshop.com',
'https://admin.myshop.com'
];
app.use(cors({
origin: function (origin, callback) {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error('Origin not allowed by CORS'));
}
},
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true
}));Understanding the Options
origin
This option sets which websites may call the API. It accepts a string, a list, or a function.
methods
This option lists the HTTP methods the API accepts from other origins.
allowedHeaders
This option lists the request headers the browser may send. Include Authorization when the frontend sends tokens.
credentials
This option lets the browser send cookies with cross-origin requests. The origin cannot be a wildcard when credentials are on. Name each trusted origin instead.
Apply CORS to One Route
Global setup is common. A single public route can also carry its own policy.
app.get('/api/public-news', cors(), (req, res) => {
res.json({ headline: 'Open to all sites' });
});Common Mistakes
- Placing cors after the routes. Register it before them.
- Using a wildcard origin together with credentials.
- Forgetting the Authorization header in allowedHeaders.
- Treating CORS as a login system. CORS only guides browsers. Tools like curl ignore it, so the API still needs authentication.
- Typing the origin with a trailing slash. The match must be exact.
Debugging CORS Errors
The browser console prints a clear message when CORS blocks a call. Read the message and compare the origin in it with the allowed list. Check the response headers in the browser network tab. A missing Access-Control-Allow-Origin header means the API did not approve the caller.
