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:
- The request url contains the
?preview=true
parameter, so always force origin request even if the request is already cached in CloudFront - 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 - 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);
};