How to invalidate cloudfrontcahce for a specific folder on S3 in NodeJS?

3.3k views Asked by At

I would like to invalidate a folder (and the subfolders) in the s3 bucket in node js. This is the script I am using at the moment:

var clearCloudfrontCache = function() {
    console.log("clearCloudfrontCache function started");
    var cloudfront = new AWS.CloudFront();
    var currentTimeStamp = new Date().getTime();
    var params = {
        DistributionId: distribution_ID,
        InvalidationBatch: {
          CallerReference: currentTimeStamp.toString(),
          Paths: {
            Quantity: NumberOfFiles,
            Items: FormerFiles
          }
      }
    };
    cloudfront.createInvalidation(params, function(err, data) {
      if (err) {
        console.log("Error came while cloudfront cache removal",err);
      }
      else {
        console.log("Cloudfront cache removed",data);
      }
    });

and this is the answer i get:

Error came while cloudfront cache removal InvalidArgument: Your request contains one or more invalid invalidation paths.
    at Request.extractError (/app/node_modules/aws-sdk/lib/protocol/rest_xml.js:53:29)
    at Request.callListeners (/app/node_modules/aws-sdk/lib/sequential_executor.js:106:20)
    at Request.emit (/app/node_modules/aws-sdk/lib/sequential_executor.js:78:10)
    at Request.emit (/app/node_modules/aws-sdk/lib/request.js:688:14)
    at Request.transition (/app/node_modules/aws-sdk/lib/request.js:22:10)
    at AcceptorStateMachine.runTo (/app/node_modules/aws-sdk/lib/state_machine.js:14:12)
    at /app/node_modules/aws-sdk/lib/state_machine.js:26:10
    at Request.<anonymous> (/app/node_modules/aws-sdk/lib/request.js:38:9)
    at Request.<anonymous> (/app/node_modules/aws-sdk/lib/request.js:690:12)
    at Request.callListeners (/app/node_modules/aws-sdk/lib/sequential_executor.js:116:18)
1

There are 1 answers

0
JavaThunderFromDownunder On

Your issue may occur if your folder has a space in the name, or any other unsupported url character.

As a path to investigate this, try posting any values via the CloudFront console to figure out which it is complaining about. The wildcard should not be an issue.

Also, fyi, if you're looking to use the latest version of the AWS api, try something like the following

const { CloudFrontClient, CreateInvalidationCommand } = require('@aws-sdk/client-cloudfront')

module.exports.createInvalidation = async (distributionId, path) => {
  const client = new CloudFrontClient()

  const params = {
    DistributionId: distributionId,
    InvalidationBatch: {
      CallerReference: String(new Date().getTime()),
      Paths: {
        Quantity: 1,
        Items: [path]
      }
    }
  }

  const createInvalidationCommand = new CreateInvalidationCommand(params)

  const response = await client.send(createInvalidationCommand)

  console.log('Posted cloudfront invalidation, response is:')
  console.log(response)
}