Hash a custom ETag in Lambda

Viewed 61

I have a custom Origin that doesn't provide ETags. I'm using Lambda@Edge to insert a custom ETag response header using Javascript into my Cloudfront distribution.

exports.handler = async (event, context) => {
    const response = {
        status: '200',
        statusDescription: 'OK',
        headers: {
            'ETag': [{
                key: 'ETag',
                value: 'test',
            }],
        },
    };

    return response;
};

I know the string I used for testing isn't going to cut it for an actual deployment. Is it possible to Hash something like the request URI from within this same JS lambda function? I'd like this to be a set-it-and-forget-it kind of setup. Most of my research shows algorithms for hashing from S3 origins which I'm not doing, and I'd also like to avoid using a node module package. Any help is appreciated!

1 Answers

Yes, ETag can be anything that identify an unique resource in some point of time.

You can create for example an etag based on body response length and current URL:

responseHeadersEtag(url, body) {
    return '"' + body.length.toString(16) + '-' + new Buffer(url).toString('base64').substring(0, 27) + '"';
}

And use it as (for example):

headers['ETag'] = responseHeadersEtag(url, request.Response.body);
Related