Unlocking the Power of Cross-Origin Resource Sharing (CORS)
Have you ever encountered an error while fetching data from an API on your website using fetch()
? The error message might have read, “No Access-Control-Allow-Origin header is present on the requested resource” or “The Access-Control-Allow-Origin header has a value
What is CORS?
CORS, or Cross-Origin Resource Sharing, is not an error itself, but rather a mechanism designed to overcome the same-origin policy enforced by web browsers. This policy restricts resource sharing across different origins, which are defined as a combination of scheme, domain, and port.
The Same-Origin Policy
Imagine your web browser as a strict gatekeeper, only allowing interactions between resources from the same origin. This is the same-origin policy in action. Modern web browsers follow this policy to prevent malicious scripts from accessing sensitive data on other websites. However, this policy also creates challenges for developers who need to fetch data from different origins.
CORS to the Rescue
CORS is an HTTP header-based protocol that enables resource sharing between different origins. By setting specific headers, servers can indicate which origins are allowed to access their resources. There are several key headers involved in CORS:
- Access-Control-Allow-Origin: specifies the allowed origins
- Access-Control-Allow-Methods: specifies the allowed HTTP methods
- Access-Control-Allow-Headers: specifies the allowed HTTP headers
- Access-Control-Max-Age: specifies the cache time for pre-flighted requests
Simple Requests vs. Pre-Flighted Requests
Not all requests trigger a CORS preflight. Simple requests must meet certain conditions, including using GET, POST, or HEAD methods, having only CORS-safe listed headers, and having a specific Content-Type. If these conditions are not met, the request is considered pre-flighted, and the browser sends an OPTIONS request to the server to check if the actual request is safe to send.
Enabling CORS
There are two scenarios to resolve CORS issues: when you have access to the backend and when you only have access to the frontend. In the former case, you can configure the server to respond with appropriate CORS headers. In the latter case, you can use a proxy server, such as cors-anywhere, to add CORS headers to the proxied request.
Tackling CORS Errors
Now that you understand CORS, you’re equipped to tackle those frustrating error messages. Whether you work on the frontend or backend, you can appreciate the same-origin policy for its security benefits while using CORS to enable resource sharing across different origins.