🌐
HTTP15M+/wkMIT

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
npm install cors
yarn
yarn add cors
pnpm
pnpm add cors

Import

ESM
import cors from 'cors';

Quick Example

usage
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

Packagecors
CategoryHTTP
Weekly Downloads15M+
LicenseMIT
Installnpm install cors

Related Packages

Browse npm Packages by Category

Explore our reference of 200 popular npm packages with install commands, examples, and quick-start guides.