I am trying to capture location of the user who calls the cloudfront dns end point to access cat.jpg. Ex: https://myrepourl.company.com/cat.jpg. The user can be from any country across the globe.
In the Cloudfront cache behavior, header 'CloudFront-Viewer-Country' is added. I have added custom policy in the response header policy and added header 'CloudFront-Viewer-Country' in this as well.
I have associated a lambda edge function (from us-east-1) to the origin response to pass the viewer country along with response headers and below is the code used.
'use strict';
exports.handler = (event, context, callback) => {
const request = event.Records[0].cf.request;
const response = event.Records[0].cf.response;
response.headers['cloudfront-viewer-country'] = request.headers['cloudfront-viewer-country']
return callback(null,response);
};
This is working fine. However, I want the lambda edge to get triggered only for calls made for cat.jpg. I would be concerned if lambda edge gets triggered for all calls made resulting in latency. Any suggestions would be very helpful.
Take a look at the PathPattern value in cache behaviors.
Lambda@Edge functions are attached at the cache behavior level. You can create a new cache behavior for this specific path pattern (route). Only matching requests will match the cache behavior and execute the associated Lambda@Edge function. All other requests will match other cache behaviors and not execute this Lambda@Edge function.
e.g., with the sample path above, your path pattern would be
/cat.jpg