0
votes

I'm trying to set a custom cloudfront response header. I created a lambda function with nodejs 12.x, added the trigger CloudFront, distribution using the correct ID, cache as *, event as Viewer response, then deploy.

Then I went to CloudFront > Distributions > IDxxx > Behaviors > Edit > * It shows the lambda function listed as Viewer Response.

When I access any from that cloudfront distribution (cache disabled locally/cloudfront miss as well), the header is never sent in the response. In CloudWatch, I see logs from the "Test" button, but none from production, so I assume that the function isn't being executed on CloudWatch, despite it being in the behaviors.

'use strict';

exports.handler = (event, context, callback) => {
    try { 
        console.log("REQUEST");
        const response = event.Records[0].cf.response;
        const headers = response.headers;
         
        response.headers['test'] = [{key: 'test', value: 'test'}];
         
        callback(null, response);
    } catch(err) {
        console.log("ERROR");
        console.log(err);
        
    }
};

Edit: Also I did use Publish new version. I assume that once it's published, cloudfront should be automatically using it?

1
Can you see the LAmbda output in the CloudWatch logs?Chris Williams
Cloudwatch has logs from the tests, but i don't see any from cloudfront requests.Caleb Pitman
Look in the region closest to you, this is where they appear for Lambda@Edge :)Chris Williams
Struggled for a couple hours with this, and 10 mins after posting I get it figured. So after publishing, have to deploy it again as well. The version is shown at the end of the lamda function in cloudfront: "...50:function:functionname:3"Caleb Pitman
Ah right, glad you got it sorted :)Chris Williams

1 Answers

1
votes

After changing a lambda function, it must be published, and then deployed again.

In CloudFront, it shows the lambda function string like: arn:aws:lambda:us-east-1:000000000000:function:testfunction:3

The end "3" is the version number. If you published 3 versions, you'll need it to show 3. Mine was still set to 1.