cors
Express and Node middleware that sets CORS response headers and handles preflight OPTIONS requests.
Official Documentation ↗cors v2.8.x / Express 4.x / Node 18 LTS. Check the official docs for the latest API surface.Installation
npm install corspnpm add corsyarn add corsMethods
No methods match this filter.
Overview
The cors middleware adds the access-control headers browsers require for cross-origin requests and answers preflight OPTIONS calls. It supports static and dynamic origin policies plus credentials.
Core Methods
Apply cors() globally or per route. Options control origin, methods, allowed headers, exposed headers, credentials and max age. An origin function decides dynamically per request.
Usage Notes
Use an explicit allowlist in production, enable credentials only when needed, and ensure the OPTIONS route is handled. Set a sensible max age to reduce preflight traffic.
Common Pitfalls
Reflecting arbitrary origins defeats the policy. A wildcard origin with credentials is rejected by browsers. Because CORS is browser-enforced, it does not prevent server-to-server access.
FAQ
- Why does the browser still block my request?
- Check that the Allow-Origin value matches the request origin exactly, including scheme and port. Wildcards cannot be combined with credentials, and a missing preflight handler causes failure before the real request.
- What does credentials: true change?
- It allows cookies and auth headers on cross-origin requests, which requires a specific origin rather than a wildcard and requires the client to send credentials.
- Is CORS a server security control?
- CORS is enforced by browsers, not servers, so non-browser clients ignore it. Protect data with authentication and authorization; treat CORS as a browser-focused policy.
Report a problem with this API docOpens a pre-filled issue on GitHub.