What is CORS? — Cross-Origin Resource Sharing Explained
Definition
CORS (Cross-Origin Resource Sharing) is a browser security mechanism that controls how web pages can request resources from a different origin (domain, protocol, or port) than the one that served the page. It is an extension of the same-origin policy, which by default prevents JavaScript on page A from reading responses from a request to server B. CORS allows servers to explicitly declare which origins are permitted to access their resources through a set of HTTP response headers.
How It Works
When a browser makes a cross-origin fetch request, it checks whether the request is "simple" (certain methods and headers only) or requires a preflight. For non-simple requests, the browser first sends an HTTP OPTIONS request (the preflight) to the target server asking if the real request is allowed. The server responds with CORS headers like Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers. If the preflight is approved, the browser sends the actual request. If any CORS check fails, the browser blocks the response — the request reaches the server, but JavaScript cannot read the response.
Common Use Cases
- ▸Allowing a frontend app on app.example.com to call an API on api.example.com
- ▸Enabling third-party JavaScript widgets to call their own backend APIs
- ▸Configuring a CDN to serve fonts or assets to any domain
- ▸Setting up a public API that allows requests from any origin with *
- ▸Debugging CORS errors during local development when the dev server differs from the API
Example
// Server response headers that allow CORS: Access-Control-Allow-Origin: https://app.example.com Access-Control-Allow-Methods: GET, POST, PUT Access-Control-Allow-Headers: Content-Type, Authorization Access-Control-Max-Age: 86400 // Allow all origins (public API): Access-Control-Allow-Origin: *
Related Tools
FAQ
- Why does CORS only affect browser JavaScript, not curl or Postman?
- CORS is enforced by the browser, not the server. curl and Postman are not browsers and do not implement the same-origin policy. The CORS headers tell the browser whether to allow the JavaScript on the page to read the response — they do not actually prevent the request from reaching the server.
- What is a CORS preflight request?
- A preflight is an automatic OPTIONS request sent by the browser before non-simple cross-origin requests. It asks the server if the actual request (with its method, headers, and origin) is permitted. The server's response either allows the browser to proceed or causes the browser to block the request with a CORS error.
- How do I fix a CORS error in development?
- In development, configure your API server to include Access-Control-Allow-Origin: http://localhost:3000 (your dev server URL) in responses. Alternatively, use a proxy in your frontend dev config (Next.js rewrites, webpack-dev-server proxy) to make requests appear same-origin.