How do I detect with Javascript If a cached version is being served from CloudFront?

I’ve enabled CloudFront to cache all articles within the website that are older than 12 hours, using cache-control. If an article gets modified, then we invalidate.

However, there are circumstances in which I need to check if the user is being served a cached version from cloudfront or not. I know that cloudfront send an HTTP response header called X-Cache which will contain "Hit from Cloudfront" in case the page is being served from the cache and "Miss from Cloudfront" if it had to request the page to our server in order to serve this request.

I’m trying to figure out ways to detect it properly. I know that with Javascript it’s currently not possible to read current headers, so I thought a good solution would be to create a CloudFront function that sends a cookie with the content of the x-cache header. And then I’d easily read that cookie locally with Javascript. This is the CloudFront function that fires at viewer response.

function handler(event) {
    var cookies = event.response.cookies;
    if (response.headers['x-cache']){
    cookies['x-cache'] = {value: response.headers['x-cache'].value};
    }
    return response;
}

This unfortunately didn’t work and my guess is that CloudFront sets the "X-Cache" response header after cloudfront functions are executed, and that is why I’m getting no x-cache cookie.

Any ideas on how to achieve what I’m trying to do?

Source: Ask Javascript Questions

LEAVE A COMMENT