Enable CORS on AWS Lambda

mohit thakur
1 min readJul 28, 2022

There are few ways in which you can support CORS for your lambda function on AWS

  • API Gateway
  • Handle CORS inside lambda function

So what is CORS?

Browsers way to protect resources from being accessed from different domains.

In lay man , `abc.com` cannot access resources from `def.com` until def.com has CORS enabled

API Gateway

  • Goto AWS management console , search for API Gateway
  • Find the API gateway that triggers your Lambda function
  • Select Enable Cors from actions . this should do the job for you.

Handle CORS using Lambda Function

Add ‘ Access-Control-Allow-Origin’: ‘*’ header to all response headers

example: handle OPTIONS request

// handle preflight request from all origins

if (event.httpMethod == 'OPTIONS') {
return {
statusCode: 200,
headers: {
'Access-Control-Allow-Headers': 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': 'true',
},
body: JSON.stringify({ message: 'Success' }),
isBase64Encoded: false,
};
}body: JSON.stringify({ message: 'Success' }),
isBase64Encoded: false,};}

This is example reference you might need to adapt a bit according to your needs!!

Happy Coding !!

--

--