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.
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.
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-Originmust match the frontend's domain or be set as a wildcard (
Access-Control-Allow-Methodsshould include the necessary methods (e.g.,
Access-Control-Allow-Headersshould include all headers sent by the frontend in the preflight request, as they will be repeated in this subsequent request.
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:
This involves creating a
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.