4
votes

I am using lambda@edge to redirect my sites with cloudfront.

I have attached my versioned lambda arn to my cloud front cache behavior to all 4 events it has.

when i hit my cloudfront endpoint it says

502 ERROR
The request could not be satisfied.
The Lambda function returned invalid json: The json output must be an object type. 

when i check my lambda logs / invocation metrics i dont see any hits at all .

what may be the reason behind this ?

i tried my best to find the fix why my lambda is not getting triggered ??

2
Clearly, from the error, your function is being triggered. It is returning an invalid response, which CloudFront rejects and renders as a 502 Bad Gateway error. Please show your code.Michael - sqlbot
You will find the logs and metrics in the region nearest the edge that is closest to the viewer -- not necessarily us-east-1. Lambda@Edge is globally distributed and runs the functions closer to where they are requested.Michael - sqlbot

2 Answers

11
votes

There are some common "gotchas" to Lambda@Edge and CloudFront. You need to:

  • Publish a new version of you Lambda function
  • Update the CloudFront Lambda association to your new version, e.g. arn:aws:lambda:us-east-1:572007530218:function:gofaas-WebAuthFunction:45
  • Look for Lambda@Edge logs in the region of the requestor

This is different from "normal" Lambda web console flow of saving a code change and jumping to logs from the monitoring tab.

2
votes

i missed adding region under the header in my lambda code.

since lambda@edge runs in the edge location we need to mention the region dynamically so that it knows where to write the logs when its running in the nearest edge location.

'x-lae-region': [ { key: 'x-lae-region', value: process.env.AWS_REGION } ]

const response = {
        status: '302',
        statusDescription: 'Found',
        headers: {
            location: [{
                key: 'Location',
                value: 'http://<destinationdomainname>/goto/hello.html',
            }],
            'x-lae-region': [ { key: 'x-lae-region', value: process.env.AWS_REGION } ],
        },
    };