CORS (Cross-Origin Resource Sharing)
Overview
CORS (Cross-Origin Resource Sharing) is a security mechanism that controls how a web browser makes requests to a different origin (the combination of protocol + domain + port). By default, browsers apply the Same-Origin Policy and restrict requests from JavaScript to a different origin. CORS provides a way to let through only requests from origins the server has explicitly allowed.
Why the Same-Origin Policy is needed
Without the Same-Origin Policy, a malicious website could send requests through the user's browser to a bank site or social network the user is logged in to and read the responses. Because the browser attaches cookies automatically, even a request sent from an attacker's site reaches the server with the user's credentials included.
CORS is designed as an "exception mechanism" that keeps this policy in place while making legitimate communication between different origins possible.
How preflight requests work
For requests to a different origin other than simple requests (GET, HEAD, and POST with certain Content-Types), the browser sends a "preflight request" using the OPTIONS method before the actual request. The server responds with headers such as Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers to state which origins, methods, and headers it allows.
The browser checks the preflight response and sends the actual request only if it's allowed. This two-step mechanism lets the server decide whether to accept a request before processing the actual request.
CORS design in a question box service
When the frontend and the backend API run on different origins, CORS needs to be configured. In a setup that uses CloudFront to place the frontend and the API on different paths of the same domain, the origin is the same, so CORS problems don't occur.
This "same-origin setup" is a design technique for avoiding the complexity of CORS. By routing /api/* paths to the API and everything else to the frontend, every request looks like a request to the same origin from the browser's point of view. This eliminates security holes from misconfigured CORS headers and added latency from preflight requests.