Deleting files from S3 and CloudFront | Invalidate CloudFront Cache


This video is part of the following playlists:


When you delete an image from s3, it stays in the CloudFront cache until the cache is cleared, usually 24 hours. In this video, learn how to invalidate the cloud front cache so that any updates or deletes to a file are immediately seen in CloudFront.

Chapters:

  • 0:00​ Intro
  • 1:28 Adding the CloudFront client
  • 5:38 IAM
  • 7:44 Summary

Code

https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-cloudfront/index.html

Install and import the CloudFront client

npm i @aws-sdk/client-cloudfront
import { CloudFrontClient, CreateInvalidationCommand } from "@aws-sdk/client-cloudfront"

Create a CloudFront object

const cloudfrontDistributionId = process.env.CLOUDFRONT_DISTRIBUTION_ID

const cloudfront = new CloudFrontClient({
  credentials: {
    accessKeyId: accessKey,
    secretAccessKey: secretAccessKey,
  }
});

Create an invalidation command

const cfCommand = new CreateInvalidationCommand({
  DistributionId: cloudfrontDistributionId,
  InvalidationBatch: {
    CallerReference: post.imageName,
    Paths: {
      Quantity: 1,
      Items: [
        "/" + post.imageName
      ]
    }
  }
})

const response = await cloudfront.send(cfCommand)

Find an issue with this page? Fix it on GitHub