0

I am working on a feature where the incoming requests from CloudFront are intercepted using Lambda Edge and then the program checks if there is a jpg file of same name present in S3. If yes, it updates the request to use jpg file otherwise use png file.

In the logs, I see a request coming in and the request getting updated with the jpg url in case a jpg file exists. But, on the webpage I still png file in every case.

Can anybody please advise what I am doing wrong?

Here's the code:

exports.handler = async (event, context, callback) => {

const request = event.Records[0].cf.request;
const headers = request.headers;
const origin = request.origin;

console.log("Original Request: " + request.uri);

if(request.uri.startsWith('/looks/') && request.uri.endsWith('.png')) {
    var jpg_file = request.uri.replace(".png", ".jpg");
    console.log("Modified Request: "+ jpg_file);
 
    var jpgFileExists = checkIfFileExists(s3, jpg_file.substr(1));

    jpgFileExists.then(function(result) {
        const type = result;
        
        console.log("TYPE: " + type);
        
        if(type) {
            console.log("send JPG file");
            request.uri = jpg_file;
        } else {
            console.log("send png file");
            //do nothing
        }
        
    }); 
}

console.log("FINAL URL: " + request.uri);

return callback(null, request);
};


async function checkIfFileExists(s3, fileName) {
let exist = true;
let params = {
    Bucket: "bucketName",
    Key: fileName
};

try {
    console.log("Checking for file: " + fileName);
    await s3.headObject(params).promise();
} catch (err) {
    exist = false;
}

console.log("EXISTS: " + exist);

return exist;

}

Ambidextrous
  • 882
  • 2
  • 12
  • 26
  • *"But, on the webpage I still png file in every case."* It isn't clear what this means. If you are expecting the browse address bar to reflect the URI what was modified in flight inside CloudFront, that would not be the expected outcome from this code. – Michael - sqlbot Jun 23 '20 at 13:10
  • @Michael-sqlbot I am not expecting the URI to change in the address bar. But, the actual resource should update right? The image being displayed on the webpage is still the png image. I check this via the size of image. It is still more than the jpg file. – Ambidextrous Jun 23 '20 at 13:26
  • Okay, so if the logs show the expected behavior then you need to suspect the browser cache as being the cause. Look at the request and response headers in the browser's developer tools. – Michael - sqlbot Jun 23 '20 at 13:36

0 Answers0