← Back to archive

Repo of the Day

expressjs/cors

Published: Jan 19, 2023

Open repository ↗

Node.js CORS middleware

Summary

The cors package is a Node.js middleware for Express and Connect that sets CORS (Cross-Origin Resource Sharing) response headers on HTTP responses. It does not block requests itself; browsers inspect the headers it emits and decide whether JavaScript running in a web page may read the response. The library is published under the MIT license and maintained under the expressjs organization.

What it is useful for

This middleware helps when you have an Express API that a front-end served from a different origin (a different scheme, host, or port) needs to call from the browser. It removes the boilerplate of writing Access-Control-Allow-Origin and related headers by hand, and it covers the pre-flight OPTIONS requests that browsers send before "complex" requests (for example, DELETE or requests carrying custom headers). It also supports route-level configuration, which is useful when some endpoints should be open and others should be restricted to specific origins or require credentials.

A practical example from the README: enabling CORS globally with app.use(cors()) adds Access-Control-Allow-Origin: * to every response. Restricting access to a single origin looks like cors({ origin: 'http://example.com' }), and the configuration options also document matching origins against a RegExp (e.g. /example\.com$/) or against an Array of strings and regular expressions.

How engineers can use it

Install it as a Node module with npm install cors, then require('cors') and apply it to your Express app. The README shows three common patterns:

  1. Apply to every route: app.use(cors()).
  2. Apply to a single route: app.get('/products/:id', cors(), handler).
  3. For non-simple requests, add an OPTIONS handler such as app.options('/products/:id', cors()) before the route definition, or use app.options('*', cors()) to cover the whole API. When used as application-level middleware, the README notes that pre-flight requests are already handled.

For configuration that depends on the request, the origin option accepts a function that receives the incoming Origin header and a callback, which the README uses to load allowed origins from a backing database. There is also a per-request variant that takes req and a callback returning options, useful when a few routes need credentials: true while the rest use origin: '*'.

A documented limitation to keep in mind: the package only sets headers, so it does not block requests from disallowed origins, nor does it authenticate or authorize them. Non-browser clients (curl, Postman, server-to-server calls) ignore these headers entirely, so authentication and authorization must be implemented separately.