1
votes

I have a CloudFront cache behaviour configured to cache all pages under the path pattern /posts. The cache behavior is fetching the content from custom origin which is a WordPress website. I need to implement custom caching logic based on the presence of a specific query parameter of the request url. Specifically, if the request url contains the query parameter ?preview=true then I want to forward that Viewer Request to the Origin to fetch the dynamically generated page, regardless of whether the request is already cached or not.

What code should I write in my nodejs lambda edge function in order to process the following scenarios for the Viewer Request event:

  1. The request url contains the ?preview=true parameter, so always force origin request even if the request is already cached in CloudFront
  2. The request url doesn't contain ?preview=true parameter and the response is already cached in CloudFront, so just return the response from the cache
  3. The request url doesn't contain ?preview=true parameter and the response is not already cached in CloudFront, so forward the request to the origin

I have the structure of the logic provided but I can't figure out the CloudFront specific code:

 const querystring = require('querystring');
 
 exports.handler = (event, context, callback) => {
     const request = event.Records[0].cf.request;
     const params = querystring.parse(request.querystring);
    
     if (params['preview'] && params['preview'] === 'true') {
        // Force request to the origin
     } else {
         // Check if request is cached in CloudFront and 
         // - Return response if request is cached
         // - Forwrd to origin if request is not cached
     }
     
    callback(null, request);
};
1

1 Answers

2
votes

I finally came up with my own solution and it was quite simple actually. All I had to do when I detect that I want to force-forward the request to the origin, is simply append an additional query parameter to the url that will have a unique value for which I chose to add the current timestamp. Then I went to my CloudFront Cache Behaviour and I whitelisted the name of the newly appended query parameter so it is passed through CloudFront to the origin server. This effectively forced CloudFront to fetch the content from the origin server whenever the url contained the preview query string. Here is the full code for a reference:

'use strict';

 const querystring = require('querystring');
 
 exports.handler = (event, context, callback) => {
     const request = event.Records[0].cf.request;
     const params = querystring.parse(request.querystring);
     
     if (params['preview'] && params['preview'] === 'true') {
      params['le-preview-timestamp'] = new Date().getTime();
      request.querystring = querystring.stringify(params);
     }
     
     callback(null, request);
};