Understanding Cross-Origin Resource Sharing (CORS)
What is CORS?
CORS stands for Cross-Origin Resource Sharing. It's a security mechanism enforced by web browsers to protect users when accessing content online.
This policy prevents web pages from making requests to a different domain than the one the site was loaded from—unless the target server explicitly allows it. For example, if a website hosted at https://example.com
tries to access an API located at https://external-api.com
, the browser will block the request unless that API is configured to permit it.
Why does CORS exist?
The main purpose of CORS is to protect users from attacks like Cross-Site Request Forgery (CSRF). Without these restrictions, a malicious website could perform actions on behalf of a user—such as making requests to bank APIs or social media services—without the user's knowledge or consent.
// Without CORS, malicious sites could: fetch('https://your-bank.com/transfer', { method: 'POST', body: JSON.stringify({amount: 1000, to: 'attacker-account'}) }); // Using your logged-in session cookies!
How does CORS work?
When a web page attempts to access resources from a different origin, the browser automatically sends a preflight request using the OPTIONS method. This request checks whether the server allows access from the requesting origin.
If the server responds with the appropriate headers (such as Access-Control-Allow-Origin
), the browser will proceed with the main request (GET, POST, etc.). If not, the browser will block the request and display a CORS error in the console.
CORS is enforced by the browser only. Server-to-server communication or tools like cURL don't enforce CORS policies.
Common headers used with CORS:
Access-Control-Allow-Origin
Specifies which origins are allowed to access the resources.
Access-Control-Allow-Origin: https://example.com // Or to allow any origin (not recommended for production): Access-Control-Allow-Origin: *
Access-Control-Allow-Methods
Indicates which HTTP methods (GET, POST, PUT, etc.) are permitted.
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers
Defines which custom headers can be used in the request.
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Credentials
States whether credentials like cookies or authentication tokens can be included in the request.
Access-Control-Allow-Credentials: true
How to fix CORS errors?
If you're developing an application and run into CORS-related errors, the fix must be applied on the server that provides the data. You need to configure the appropriate headers to allow cross-origin access where necessary.
During development, it's common to use proxies or tools that temporarily bypass these restrictions for testing purposes. However, this approach should not be used in production environments for security reasons.