Configure CORS in Node.js and Express 5
By Ankit Jain · Updated
Use Express cors middleware with an exact origin allowlist, correct middleware order, and readable error responses.
Use the maintained cors middleware to handle preflight and response headers. This example uses the Express 5 routing style and cors 2.x API. Adapt its origin list, methods, and credentials setting to your actual API.
Install and configure
npm install express cors
const express = require('express');
const cors = require('cors');
const app = express();
const approvedOrigins = new Set([
'https://app.example.com',
'http://localhost:5173'
]);
// This policy varies by Origin, including responses to unapproved origins.
app.use((req, res, next) => { res.vary('Origin'); next(); });
app.use(cors({
origin(origin, callback) {
callback(null, origin !== undefined && approvedOrigins.has(origin));
},
methods: ['GET', 'POST', 'PUT'],
allowedHeaders: ['Content-Type', 'Authorization'],
exposedHeaders: ['X-Request-ID'],
credentials: false // Use true only for your approved cookie-session integration.
}));
app.use(express.json());
// A public demonstration route, not an authenticated profile endpoint.
app.get('/api/message', (req, res) => {
res.set('X-Request-ID', 'demo-123');
res.json({ message: 'hello' });
});
app.use((req, res) => res.status(404).json({ error: 'not_found' }));
app.use((error, req, res, next) => {
if (res.headersSent) return next(error);
res.status(500).json({ error: 'internal_error' });
});
app.listen(3000);
Why this order matters
Global cors middleware handles OPTIONS preflight requests without an additional wildcard route. Keep it before authentication and routes so 401, 404, and 500 responses that JavaScript needs to read receive permission. Gateway-generated errors need a gateway policy separately.
An older app.options('*', cors()) example can fail with Express 5’s changed wildcard route syntax. Global middleware avoids that route entirely. For route-scoped policies, use the routing syntax your installed Express version supports.
Cookie and token requests
For an approved cross-origin cookie session, set credentials: true here and credentials: include in fetch. Check cookie eligibility and credentials mode, and retain session authentication and CSRF defenses. This example does not implement a session or authentication.
For an explicitly supplied bearer token, allow Authorization in preflight and validate the token in your actual route. The credentials flag does not generate a token. An unapproved Origin receiving no CORS permission does not mean its request could not reach the server.
Verify from the frontend
- Fetch /api/message from an approved origin and read X-Request-ID.
- Send a JSON request or Authorization header and inspect OPTIONS.
- Request a missing route: its 404 should be readable from an approved origin.
- Check an unapproved origin receives no readable CORS permission.
Use DevTools for the browser path and the tester for captured headers. If the proxy also adds Allow-Origin, remove duplicate header writers before testing again.
Develop while the API is unfinished
Beeceptor can mock the response contract while you build the frontend. Configure Express’s real CORS policy separately and verify it before switching the frontend to your deployed API. Read the Beeceptor mock-rule guide.