Configuring API Gateway for CORS

In this lesson, you will learn how to configure API Gateway for CORS using AWS Lambda.

We'll cover the following

OPTIONS handler #

The CORS request going from the web page to your API is going to be a bit more tricky. You’ll need to add an OPTIONS handler to the API and also change the response in your function to include the correct origin.

There are two ways of configuring OPTIONS handlers. The first is to add a Lambda function and an API endpoint. This would make it fully flexible, so you could dynamically calculate the right origin and response headers, but it would add an API call and a Lambda execution to your costs. In cases where you don’t really need a dynamic response, such as where you always have a single valid origin, you could also just configure a static response in the API Gateway. This requires no backing Lambda, so it is cheaper but less flexible.

SAM has a nice shortcut for configuring a static response. Just add a Cors property to the API resource, with the supported origin. Note that this uses a slightly overcomplicated syntax. API Gateway needs quotes around header values, so you’ll need to wrap the website URL in quotes using CloudFormation string substitution. The API definition is changed in your application template to match the following listing (the important addition is in line 5).

Get hands-on with 1200+ tech skills courses.