# cors — CORS Middleware for Express and Connect > A Node.js package that provides Express/Connect middleware for enabling Cross-Origin Resource Sharing with various configuration options. Handles preflight requests and response headers automatically. ## Install Save in your project root: # cors — CORS Middleware for Express and Connect ## Quick Use ```bash npm install cors ``` ```js const express = require('express'); const cors = require('cors'); const app = express(); app.use(cors()); // enable all CORS requests app.get('/api/data', (req, res) => res.json({ msg: 'CORS enabled' })); app.listen(3000); ``` ## Introduction The cors package is the standard middleware for enabling Cross-Origin Resource Sharing in Express.js applications. It handles the HTTP headers and preflight OPTIONS requests that browsers require when a frontend on one domain communicates with an API on another, saving developers from manually managing CORS headers. ## What cors Does - Adds the correct Access-Control-Allow-Origin and related CORS headers to HTTP responses - Automatically responds to preflight OPTIONS requests with the configured allowed methods and headers - Supports dynamic origin validation via callback functions for multi-tenant or whitelist scenarios - Allows per-route CORS configuration by applying the middleware selectively - Handles credentials, exposed headers, and max-age for preflight caching ## Architecture Overview The cors middleware intercepts incoming requests and injects CORS headers into the response based on the provided configuration object. For simple requests, it adds Access-Control-Allow-Origin directly. For preflight requests (OPTIONS method with specific headers), it responds immediately with the full set of allowed methods, headers, and credentials flags without passing the request to downstream handlers. The origin option accepts a string, regex, array, or function, enabling flexible origin matching. ## Self-Hosting & Configuration - Install via npm and add as Express middleware with app.use(cors(options)) - Set a specific origin: `cors({ origin: 'https://example.com' })` - Allow multiple origins with an array: `cors({ origin: ['https://a.com', 'https://b.com'] })` - Enable credentials (cookies, auth headers): `cors({ credentials: true })` - Configure per-route by passing cors() as route-level middleware instead of app-level ## Key Features - Zero-config default mode that allows all origins — useful during development - Dynamic origin validation with async callbacks for production whitelisting - Automatic preflight handling with configurable max-age caching - Per-route middleware support for fine-grained CORS policies - Follows the CORS specification for Access-Control-Expose-Headers and Access-Control-Allow-Credentials ## Comparison with Similar Tools - **Manual header setting** — error-prone and requires handling preflight logic yourself; cors abstracts it - **Helmet** — security middleware that sets various HTTP headers but does not handle CORS; complementary to cors - **@fastify/cors** — equivalent plugin for Fastify; uses a similar configuration API - **NGINX/proxy-level CORS** — handles CORS at the reverse proxy layer; useful when the app server should not manage it ## FAQ **Q: How do I allow all origins?** A: Call `cors()` with no arguments or set `origin: true`. This sets Access-Control-Allow-Origin to the request's Origin header. **Q: Can I validate origins dynamically?** A: Yes. Pass a function as the origin option: `origin: (origin, callback) => { /* check origin, call callback(null, true/false) */ }`. **Q: Why does my browser still block requests after adding cors?** A: Ensure the middleware runs before your route handlers and that you handle OPTIONS requests. Also check that credentials mode matches between frontend and backend. **Q: Does cors work with non-Express frameworks?** A: It works with any Connect-compatible framework. For Fastify, Koa, or Hono, use their native CORS plugins. ## Sources - https://github.com/expressjs/cors - https://www.npmjs.com/package/cors --- Source: https://tokrepo.com/en/workflows/asset-c0cabafd Author: AI Open Source