CORS (Cross-Origin Resource Sharing) is a security mechanism implemented by web browsers to control which websites can access resources from other domains. By default, browsers block cross-origin requests—requests made from one website to another domain, protocol, or port—for security reasons.
Without CORS, malicious websites could secretly send requests to other servers (e.g., API servers or banking sites), potentially stealing or misusing sensitive data (Cross-Site Request Forgery, CSRF). CORS ensures that only explicitly allowed websites can access resources.
When a web application makes a cross-origin request (e.g., from http://example.com
to https://api.example.com
), the browser automatically sends a CORS request. The server must then respond with specific HTTP headers to indicate whether the request is allowed:
Without CORS headers:
The browser blocks the request.
With CORS headers:
The server can respond with Access-Control-Allow-Origin: *
(allowing all domains) or a specific domain (Access-Control-Allow-Origin: https://example.com
). This enables access.
For certain requests (e.g., PUT
, DELETE
, or requests with custom headers), the browser sends a preflight request using the OPTIONS
method. The server must respond with the correct CORS headers to allow the main request.
CORS is a crucial security measure that prevents unauthorized websites from accessing foreign resources. Developers must configure the correct server-side headers to allow legitimate clients to access the data.