cors
CORS middleware for Express — configure cross-origin resource sharing with a single line of code.
cors
ExpressCORS middleware for Express — configure cross-origin resource sharing with a single line of code.
Fit
Bundle (gzip)
1.9 kB
4.3 kB raw
Install size includes transitive dependencies. Bundle size is gzipped browser payload.
Freshness
The Problem
Browser security blocks cross-origin API requests by default. Configuring CORS headers correctly — including preflight OPTIONS responses, allowed origins, credentials, and methods — requires careful implementation that's easy to get wrong.
What It Does
The cors middleware handles all CORS header logic for Express. You can allow all origins, restrict to a whitelist, configure per-route, and handle preflight automatically. The options mirror the CORS spec exactly — origin, methods, allowedHeaders, credentials, maxAge.
Installation
npm install cors
npm install -D @types/corsUsage Example
import express from 'express';
import cors from 'cors';
const app = express();
// Allow specific origins
app.use(cors({
origin: ['https://myapp.com', 'https://staging.myapp.com'],
methods: ['GET', 'POST', 'PUT', 'DELETE'],
credentials: true,
}));
// Or per-route
app.get('/public', cors(), (req, res) => {
res.json({ data: 'accessible from anywhere' });
});Related packages
Node.js body parsing middleware — populate `req.body` from JSON, urlencoded, text, and raw payloads.
compressionExpressHTTP response compression middleware for Express — gzip/deflate responses to reduce bandwidth and improve load times.
cookie-parserExpressCookie parsing middleware for Express — parse Cookie headers into `req.cookies` and support signed cookies for tamper detection.
express-async-errorsExpressSimplify Express error handling by automatically passing thrown errors to `next()`.
express-fileuploadExpressSimple Express middleware for handling `multipart/form-data` file uploads, built on Busboy.