Home > Blockchain >  How to correctly configure APIGateway for CORS using the CDK
How to correctly configure APIGateway for CORS using the CDK

Time:10-19

I have an API provided by AWS ApiGateway, backed by an AWS Lambda function and provisioned using the CDK. The API has been configured with default CORS settings:

const api = new apiGateway.RestApi(this, "comments-api", {
  defaultCorsPreflightOptions: { allowOrigins: apiGateway.Cors.ALL_ORIGINS }
})

const comments = api.root.addResource("comments")

const comment = comments.addResource("{post_slug}")

comment.addMethod("GET", new apiGateway.LambdaIntegration(listCommentsFunction))

This appears to provide only part of the CORS configuration for my API.

  • It provides a response to an OPTIONS request with the appropriate CORS related headers but
  • It seems it does NOT hydrate the response to a request to GET <api>/comments/{post_slug} with the appropriate CORS headers

This makes the CORS configuration options in the CDK construct not particularly useful - since it seems more sensible for me to ignore that setting and instead manually configure an OPTIONS response from my Lambda, by changing it to this:

const api = new apiGateway.RestApi(this, "comments-api")

const comments = api.root.addResource("comments")
const comment = comments.addResource("{post_slug}")

comment.addMethod("GET", new apiGateway.LambdaIntegration(listCommentsFunction))
comment.addMethod("OPTIONS", new apiGateway.LambdaIntegration(listCommentsFunction))

And then ensuring that my lambda always responds with the correct headers. If I don't do this, then I'm hydrating my responses with CORS headers using two different mechanisms; CDK stack configuration and explicit handler logic. This feels like a smell.

I'm wondering for this reason if I'm misconfiguring something and there is a way to use the CDK to configure the response to be correctly hydrated as well.

CodePudding user response:

CDK generated code for the OPTIONS method is using response overrides - https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-override-request-response-parameters.html

This option is not available in the lambda proxy integration, which you are using for the GET method. I did not found indeed any other option than to calculate the CORS headers on the lambda source code level.

P.S.: I wrote https://milangatyas.com/Blog/Detail/14/setup-cors-for-amazon-api-gateway-via-aws-cdk where you can get more detailed information.

  • Related