Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make CloudFront never cache index.html on S3 bucket

I have a React app hosted on an S3 bucket. The code is minified using yarn build (it's a create-react-app based app). The build folder looks something like:

build ├── asset-manifest.json ├── favicon.ico ├── images │   ├── map-background.png │   └── robot-icon.svg ├── index.html ├── js │   ├── fontawesome.js │   ├── packs │   │   ├── brands.js │   │   ├── light.js │   │   ├── regular.js │   │   └── solid.js │   └── README.md ├── service-worker.js └── static     ├── css     │   ├── main.bf27c1d9.css     │   └── main.bf27c1d9.css.map     └── js         ├── main.8d11d7ab.js         └── main.8d11d7ab.js.map 

I never want index.html to be cached, because if I update the code (causing the hex suffix in main.*.js to update), I need the user's next visit to pick up on the <script src> change in index.html to point to the updated code.

In CloudFront, I can only seem to exclude paths, and excluding "/" doesn't seem to work properly. I'm getting strange behavior where I change the code, and if I hit refresh, I see it, but if I quit Chrome and go back, I see very outdated code for some reason.

I don't want to have to trigger an invalidation on every code release (via CodeBuild). Is there some other way? I think one of the challenges is that since this is an app using React Router, I'm having to do some trickery by setting the error document to index.html and forcing an HTTP status 200 instead of 403.

like image 780
ffxsam Avatar asked Aug 17 '17 05:08

ffxsam


People also ask

How do I make CloudFront not cache?

On your custom origin web server application, add Cache-Control no-cache, no-store, or private directives to the objects that you don't want CloudFront to cache. Or, add Expires directives to the objects that you don't want CloudFront to cache.

How do I turn off Amazon CloudFront?

In the right pane of the CloudFront console, select the check box for the distribution that you want to delete. Choose Disable to disable the distribution, and choose Yes, Disable to confirm. Then choose Close.

How do I set cache policy in CloudFront?

Open the CloudFront console at https://console.aws.amazon.com/cloudfront/v3/home . Choose Create distribution. In the Cache key and origin requests section, make sure that Cache policy and origin request policy is chosen. For Cache policy, choose the cache policy to attach to this distribution's default cache behavior.


1 Answers

A solution based on CloudFront configuration:

Go to your CloudFront distribution, under the "Behavior" tab and create a new behavior. Specify the following values:

  • Path Pattern: index.html
  • Object Caching: customize
  • Maximum TTL: 0 (or another very small value)
  • Default TTL: 0 (or another very small value)

Save this configuration.

CloudFront will not cache index.html anymore.

like image 125
seza443 Avatar answered Sep 28 '22 10:09

seza443