Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add CORS headers on 5XX responses from API Gateway with Lambda proxy integration

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?

like image 930
Yannick Blondeau Avatar asked May 02 '18 15:05

Yannick Blondeau


People also ask

How do I enable CORS on API gateway with Lambda proxy integration?

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.

Does API gateway pass headers to Lambda?

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.


1 Answers

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]

like image 153
Dale Jacques Avatar answered Oct 05 '22 19:10

Dale Jacques