CORS
CORS (Cross-Origin Resource Sharing) is a crucial security feature designed for frontend applications using HTML/JS, allowing them to make requests to backends on different domains. CORS doesn't apply to tools like curl or mobile applications.
Preflight Requests
When a browser intends to make a request (e.g., GET https://domain.com/path
), it initiates a preflight request OPTIONS https://domain.com/path
with the same headers as the actual request. In response, the backend communicates with the frontend by sending CORS headers. These headers serve as a means to inform the browser whether or not it's allowed to execute the actual request in a frontend code running in a web browser.
Request Handling
If the preflight request satisfies the CORS headers returned by the backend, the browser proceeds to send the actual request GET https://domain.com/path
. This step occurs only when specific criteria are met:
Access-Control-Allow-Origin
must match the frontend's domain or be set as a wildcard (*
).Access-Control-Allow-Methods
should include the necessary methods (e.g.,GET
).Access-Control-Allow-Headers
should include all headers sent by the frontend in the preflight request, as they will be repeated in this subsequent request.
Example
Access-Control-Allow-Origin: https://domain.com/path
Access-Control-Allow-Methods: GET, POST, PATCH
Access-Control-Allow-Headers: Authorization, Content-Type
Implementing CORS in AWS Gateway
When dealing with AWS Gateway, there are two primary approaches:
Option 1: {proxy+}
Method
This involves creating a {proxy+}
OPTIONS
method to capture all missing routes. Since most apps don't typically serve OPTIONS
methods for any routes, this method captures all requests and returns CORS for preflight requests. The reply to the OPTIONS
method might be handled by a separate application.
Option 2: Specific OPTIONS
Method for Each Endpoint
Alternatively, you can serve an OPTIONS
method for each existing endpoint. This approach allows for more granular control, enabling the return of specific CORS headers tailored to each endpoint's requirements.