« Back to home

API Gateway: CORS

Last updated on

Setting CORS while using AWS API Gateway can be a bit confusing, as the `Enable CORS` option in the Action menu doesn't work out of the box. These are some simple steps (far from perfect) I have used to enable CORS using their console.

  1. Add the OPTIONS method to each endpoint. Configure the endpoint as a MOCK integration.


2. Β In the Method Response (Left bottom) block add Status 200 and the corresponding Response Headers `Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin`

3. In the Method Execution (Right Bottom) block, use the 200 response status created in step 2 and map headers as shown below.

Header Mappings

Access-Control-Allow-Headers
'Access-Control-Allow-Origin, Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token' 
Access-Control-Allow-Methods
'OPTIONS'
Access-Control-Allow-Origin
'*'

Mapping Template: application/json

{
    statusCode: 200,
    headers: {
        "Access-Control-Allow-Origin": "*"
    },
        body: ''
};

Some sources advise explicitly setting the header in the mapping template as well.

4. Save your changes and deploy API using the actions menu.

As mentioned in step 1, this should be repeated for each cors-enabled endpoint, that includes GET requests.

You also need to add the Access-Control-Allow-Origin: '*' mapping to your GET, POST, PUT, DELETE methods (steps 2, 3)

If you need support for more response codes (4xx, 5xx) repeat steps 2 and 3 for each code.