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:

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.