Node.js CORS middleware
The cors package is a middleware for Express.js and compatible Node.js frameworks that enables Cross-Origin Resource Sharing (CORS) by automatically configuring HTTP headers. CORS is a browser security mechanism that blocks JavaScript running on one domain from accessing resources on another domain unless explicitly allowed. This package solves the common problem developers face when their frontend (e.g., localhost:3000) needs to call APIs hosted on a different origin (e.g., api.example.com).
With over 34 million weekly downloads, cors is the de facto standard for handling CORS in the Node.js ecosystem. It provides a clean abstraction over the complex HTTP header requirements needed for both simple requests and preflight OPTIONS requests. Instead of manually setting Access-Control-* headers and handling edge cases, developers can configure CORS policies declaratively through options like allowed origins, HTTP methods, headers, and credential handling.
The package is used by companies and projects ranging from small startups to enterprise applications that need fine-grained control over which external domains can access their APIs. It supports everything from permissive development configurations (allowing all origins) to strict production setups with origin whitelisting, dynamic validation functions, and per-route policies. The middleware integrates seamlessly with Express's request pipeline and can be applied globally, selectively to specific routes, or conditionally based on runtime logic.
CORS is particularly critical for modern web architectures where frontends are decoupled from backends—whether using frameworks like React, Vue, or Angular that run on different ports during development, or deploying static frontends on CDNs while APIs run on separate infrastructure. The cors package removes the complexity of implementing this correctly while providing security controls to prevent unauthorized cross-origin access.
const express = require('express');
const cors = require('cors');
const app = express();
const allowedOrigins = [
'https://myapp.com',
'https://staging.myapp.com',
/\.myapp\.com$/
];
const corsOptions = {
origin: (origin, callback) => {
if (!origin || allowedOrigins.some(allowed =>
typeof allowed === 'string' ? allowed === origin : allowed.test(origin)
)) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true,
optionsSuccessStatus: 200,
maxAge: 86400
};
app.use('/api/public', cors());
app.use('/api/private', cors(corsOptions));
app.get('/api/public/data', (req, res) => {
res.json({ message: 'Available to all origins' });
});
app.post('/api/private/user', (req, res) => {
res.json({ message: 'Restricted to whitelisted origins' });
});
app.listen(5000, () => {
console.log('Server running on port 5000');
});Public API access: Allowing any origin to consume a public REST or GraphQL API by enabling permissive CORS headers, useful for open data services or developer platforms where third-party websites need unrestricted access.
Single-page application development: Configuring CORS during local development when a React/Vue/Angular app on localhost:3000 needs to call a backend API on localhost:5000, then tightening the policy in production to only allow the deployed frontend domain.
Microservices communication: Enabling specific internal services to communicate cross-origin in a microservices architecture, such as allowing an admin dashboard on admin.company.com to access user APIs on api.company.com while blocking other origins.
Mobile app backends: Configuring CORS for hybrid mobile apps (Ionic, React Native with WebView) that make HTTP requests from file:// or capacitor:// origins, requiring special origin handling and credentials support for authentication tokens.
Third-party integrations: Restricting API access to authorized partner domains using origin whitelisting or dynamic validation functions that check origins against a database, ensuring only approved integrations can access sensitive endpoints.
npm install corspnpm add corsbun add cors