Enabling CORS for Lambda proxy integration in AWS API Gateway (with AWS CDK)
I wanted to quickly document the process of enabling CORS when working with API Gateway’s Lambda proxy integration. Proxy integration allows you to call a Lambda function in the backend. Enabling the proxy integration removes the standard API Gateway integration response and places the responsibility of returning CORS headers in the hands of the backend service. Many questions online have emanating from this shift of responsibility. I’m hoping this article saves others time by presenting the configuration required to allow CORS requests to your APIs.
A common requirement when building APIs with AWS API Gateway (but not limited to API Gateway) is the enablement of Cross-Origin Resource Sharing(CORS). If your building a web application that happens to make requests to APIs on a different domain than enabling CORS will allow these requests succeed.
The CORS standard works by adding new HTTP headers which allows your servers (in this case the API Gateway) to describe which origins are permitted to call your API from a web browser. An initial preflight request is sent which contains the headers the browser plans to send in the actual request. This request solicits supported method and upon approval sends the actual request.
In this article I will present the configuration required to allow this exchange between browser and backend Lambda service.
AWS CDK setup for API Gateway
The AWS CDK RestApi construct automatically deploys a resource which is accessible over a public endpoint. In this example I will modify this default behavior slightly and create a custom POST endpoint named webhook. This resource represents the actual request the browser will attempt to make.
Notice that the LambdaIntegration proxy flag is enabled. Enabling this flag circumvents the need for an integration response in our API Gateway endpoint. With the removal of the integration response it is then the responsibility of the target Lambda service to return the the
Access-Control-Allow-Headers headers to enable CORS. See the AWS developer guide for a more detailed explanation.
The second resource we create is the OPTIONS resource which is needed to allow a preflight request.
Finally we return the
Access-Control-Allow-Headers headers from our GO Lambda function.
It requires an investment of your time to get comfortable with AWS CDK. In the beginning it is arguably faster just to make some of these changes through the AWS Console. Once you get over the early learning curve however and realize the benefits of a fully automated stack then there is no turning back.