Enable cross-origin API access
An API should be readable by browser clients from permitted origins.
Express.js · Module
cors is Express/Connect middleware that adds CORS response headers. Use it globally, on individual routes, or with request-dependent options so browsers can evaluate cross-origin access.
The cors middleware adds CORS response headers. Apply it globally with app.use(cors()), on selected routes with cors(), or provide static or request-dependent options; browsers then use those headers to decide whether client-side JavaScript may read the response.
cors(options)| Name | Type | Description |
|---|---|---|
options | Object | Function | Configuration options, or a function that receives the request and returns CORS options through a callback. |
Middleware function
cors() with default settings adds a wildcard Access-Control-Allow-Origin header.const express = require('express');
const cors = require('cors');
const app = express();
app.get('/products/:id', cors(), (req, res) => {
res.json({ id: req.params.id });
});
app.listen(3000);Installs CORS headers only for the product route, allowing browsers to read its response.
An API should be readable by browser clients from permitted origins.
Only selected endpoints should expose CORS headers.
Allowed origins or credentials vary with the incoming request.
A browser client sends a complex cross-origin request.
The middleware sets response headers describing permitted cross-origin access. Browsers inspect those headers and decide whether browser JavaScript can read the response; the middleware does not itself reject the request.
Follow-up: What happens with curl? It can receive the response because non-browser clients do not enforce CORS.
Use app.use(cors()) to apply it application-wide, or pass cors() as route middleware to limit it to a specific endpoint. The documentation also supports passing configuration options.
Follow-up: How can configuration vary by request? Supply a function that receives the request and returns options through the callback pattern.
A complex cross-origin request can begin with an OPTIONS pre-flight request. The route must have an OPTIONS handler when pre-flighting needs to be enabled.
Follow-up: Why may an API still appear accessible from curl? CORS is a browser policy, so curl ignores the headers.
corsAccess-Control-Allow-OriginAccess-Control-Allow-CredentialsOPTIONSpre-flight request