My API relies on AWS ApiGateway with an underlying AWS Lambda function provisioned through the CDK. The default CORS settings for the API are as follows:
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))
However, it seems that this configuration only covers part of the CORS setup for my API.
- The response to an
OPTIONS
request includes the necessary CORS headers but - It appears that the response to a
request does not include the required CORS headersGET <api>/comments/{post_slug}
As a result, relying solely on the CDK construct for CORS configuration may not be ideal. Instead, manually configuring an OPTIONS response from my Lambda function might be more effective, like so:
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))
This approach ensures that the lambda always responds with the correct headers and avoids conflicting mechanisms for adding CORS headers. It's worth exploring if there is a way to leverage the CDK to configure the response for proper hydration as well.