cors
CORS (Cross-Origin Resource Sharing) is an Express/Connect middleware that enables cross-origin requests by setting the appropriate HTTP headers. Browsers enfor…
Installation
npm install cors
yarn add cors
pnpm add cors
Import
import cors from 'cors';
Quick Example
import express from 'express';
import cors from 'cors';
const app = express();
app.use(cors({
origin: 'https://example.com',
credentials: true,
}));About cors
CORS (Cross-Origin Resource Sharing) is an Express/Connect middleware that enables cross-origin requests by setting the appropriate HTTP headers. Browsers enforce the same-origin policy by default, blocking JavaScript from making requests to a different origin (domain, protocol, or port) than the page was loaded from. The cors middleware configures the Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers, and other CORS-related headers that tell browsers which cross-origin requests to permit. The middleware supports both simple configuration (allowing all origins) and fine-grained control where you can specify allowed origins as strings, regular expressions, or functions, configure allowed HTTP methods and headers, enable credentials passing, set preflight cache duration, and handle OPTIONS preflight requests. CORS is essential for any API that needs to be consumed by frontend applications hosted on different domains, which is the standard architecture for single-page applications calling backend APIs. The middleware can be applied globally to all routes or selectively to specific endpoints. It is one of the most installed middleware packages in the Express ecosystem.
Quick Facts
| Package | cors |
| Category | HTTP |
| Weekly Downloads | 15M+ |
| License | MIT |
| Install | npm install cors |
Related Packages
Express is the most widely used web application framework for Node.js, providing a minimal and flexi…
Helmet helps secure Express.js applications by setting various HTTP response headers that protect ag…
Body-parser is a Node.js body parsing middleware that extracts the body portion of incoming HTTP req…
Compression is a Node.js middleware that compresses HTTP response bodies using gzip, deflate, or Bro…
Browse npm Packages by Category
Explore our reference of 200 popular npm packages with install commands, examples, and quick-start guides.