3

I have a Cloudfront distribution with a custom origin.

I want to use a Lambda@Edge Origin Request to modify and add some extra headers to be forwarded to my origin server.

Below is my Lambda function. The custom_header is visible in Cloudwatch logs for my Lambda, but doesn't show up in my custom server request headers :(.

exports.handler = (event, context, callback) => {
  const request = event.Records[0].cf.request;
  const headers = request.headers;

  headers['custom_header'] = [{ key: 'custom_header', value: 'custom_header' }];

  return callback(null, request);
}

I expect custom_header to be visible in my Node.js route under req.headers.

Yves M.
  • 29,855
  • 23
  • 108
  • 144
Mihai Serban
  • 241
  • 3
  • 10

2 Answers2

7

Custom header can be passed through following structure.

request.origin.custom.customHeaders

Ref: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html#lambda-event-structure-request

So, the code should look like .

exports.handler = (event, context, callback) => {
  const request = event.Records[0].cf.request;
  const headers = request.headers;

  request.origin.custom.customHeaders['custom_header'] = [{ key: 'custom_header', value: 'custom_header' }];

  return callback(null, request);
}
Sumit Kathuria
  • 103
  • 2
  • 7
  • 1
    Hi Sumit, shouldn't AWS injects the custom header automatically into the origin? I'm facing an issue that In the past was being injected, but it seems that now the header is not being passed anymore. Do you know any changelog about it on AWS side? – thiago Jul 07 '20 at 14:52
  • Is it possible to add some custom headers during viewer request? This sample code is for Origin Request. – Javier Pallarés May 07 '21 at 09:26
0

Your problem may be that you're using "Origin Request" rather than "Viewer Request" triggers.

Let's see this AWS docs article about "which trigger should I use?"

Do you want the function to execute for every request?
If you want the function to execute for every request that CloudFront receives for the distribution, use the viewer request or viewer response events. Origin request and origin response events occur only when a requested object isn't cached in an edge location and CloudFront forwards a request to the origin.

I just fixed a similar issue to yours - just that I was trying the Origin Response triggers. I had caching set up on my S3 (items uploaded with --max-age to S3), then I hosted a static site using S3 and used CloudFront on top.

I assume since my S3 items were cached, the Origin Request trigger didn't fire, because as the AWS article says - Origin Request/Response triggers fire only on cache misses.

Once I switched to Viewer Response it was ok.

I was following this tutorial, and even there the screenshot for lambda trigger setup has "Origin Response", which misled me.