Enabling CORS in AWS API Gateway

Enabling CORS for your AWS REST API

Posted on September 4, 2020

So, we’ve already created our API using AWS Lambda and API gateway.
As browsers enforce CORS (Cross-Origin Resource Sharing) we need to enable this in API gateway so that our web applications can consume our APIs data.

You can find the ‘Building an API with AWS Lambda and API gateway‘ tutorial here.

Luckily AWS make it very easy for us:

  • Navigate to the API gateway dashboard in AWS and select your API
  • Click on Your resource > Actions > Enable CORS
    This will create an ‘Options’ method and enable CORS on all methods under that resource
  • You can leave all values as default for the time being and the Access-Control-Allow-Origin default value of ‘*’ will allow requests from all origins. This can be updated at a later date to restrict origins.

Next we to redeploy our API; Select your resource > Actions > Deploy API

Then it’s just a case of updating the response in our Lambda function to return the ‘Access-Control-Allow-Origin‘ header as below.

exports.handler = async (event) => {
    
    const method = event.httpMethod;
    let response;
    
    if (method === 'GET') {
        response = {
            statusCode: 200,
            headers: {"Content-Type": "application/text", "Access-Control-Allow-Origin": "*"},
            body: JSON.stringify('GET success!'),
        };
    } else if(method === 'POST') {
        response = {
            statusCode: 200,
            headers: {"Content-Type": "application/text", "Access-Control-Allow-Origin": "*"},
            body: JSON.stringify('POST success!'),
        };
    }
    
    return response;
};

…and we’re done. We can now consume our API data in our web application.