I have a Lambda proxy integration with API Gateway that is working fine.
CORS is handled directly in the lambda code with checks against lists of authorized domains.
But the issue now is with unexpected errors during Lambda execution.
API Gateway returns the following message in such a case:
{
message: "Internal server error"
}
with a 502
HTTP status code. Unfortunately for me, the Access-Control-Allow-Origin
header is missing in that response, which is causing errors on client side.
The same happens also with timeouts for example. The HTTP status code is then 504
but the response content and the lack of Access-Control-Allow-Origin
is the same.
The same issue occurs also in case of permission issue: if the API Gateway does not have sufficient permissions to call the Lambda, then a 500
error is returned but, once again, without any header.
A fixed value of '*'
would be OK in the case of Lambda errors but how and where can this be configured?
To enable CORS for the Lambda proxy integration, you must add Access-Control-Allow-Origin: domain-name to the output headers . domain-name can be * for any domain name. The output body is marshalled to the frontend as the method response payload.
To pass custom headers from an API Gateway API to a Lambda function, use a body mapping template. The API sends the updated API request to a Lambda function to process the headers. Then, the Lambda function returns one or more header values from the original API request.
Late to the game, but you can add these to your SAM / CloudFormation template to fix this:
Resources:
GatewayResponseDefault4XX:
Type: 'AWS::ApiGateway::GatewayResponse'
Properties:
ResponseParameters:
gatewayresponse.header.Access-Control-Allow-Origin: "'*'"
gatewayresponse.header.Access-Control-Allow-Headers: "'*'"
ResponseType: DEFAULT_4XX
RestApiId:
Ref: 'ApiGatewayRestApi'
GatewayResponseDefault5XX:
Type: 'AWS::ApiGateway::GatewayResponse'
Properties:
ResponseParameters:
gatewayresponse.header.Access-Control-Allow-Origin: "'*'"
gatewayresponse.header.Access-Control-Allow-Headers: "'*'"
ResponseType: DEFAULT_5XX
RestApiId:
Ref: 'ApiGatewayRestApi'
Taken from here: [https://serverless-stack.com/chapters/handle-api-gateway-cors-errors.html#create-a-resource][1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With