Conflict between service worker and CloudFront?
ffxsam opened this issue ยท 8 comments
I'm deploying my React app to S3 behind a CloudFront distribution. With my particular process, I copy all the files to S3, and then copy index.html in the following manner:
aws s3 cp --cache-control 'public, no-cache, must-revalidate, proxy-revalidate, max-age=0' ./build/index.html $APP_BUCKET
The Cache-Control used to just be max-age=0, but I ran into problems with aggressive caching and added more options. I never want index.html to be cached, otherwise when I release updates, users would still get the old index.html pointing to the old JS files.
Now I'm wondering if the service worker is somehow getting in the way. Should I remove it since I'm using CloudFront? Or is there a better way than what I'm doing to make sure that when I deploy a code update, that users will get it next time they reload or hit the site?
Thanks.
I set the CloudFront TTLs (default, min, max) all to 0. There's still odd behavior going on. If I redeploy my updated app and then open it up, I see in the console a message telling me to refresh, that there's an update. I do so, and I see the code update, but the log says once again to refresh to get an update. That behavior seems wrong.
Any insight on how to properly deploy to S3 + CloudFront would be really helpful!
UPDATE:
I think I got it. I've left CloudFront cache settings alone (using origin headers, etc), and changed my deployment to single out these two files now:
aws s3 cp --cache-control max-age=0 ./build/index.html s3://myapp.com/
aws s3 cp --cache-control max-age=0 ./build/service-worker.js s3://myapp.com/
The service worker itself was getting cached, which is problematic.
But someone let me know if there's a better way still. ๐
You are on right track. service-worker.js should not be cached
@ffxsam could you please verify these settings for my cloudfront
@ffxsam do your users need to refresh their page or revisit their links for their cache to get updated?
Hey guys, just wanted to reply and say that since my last post, I've started using Netlify for deployment. It's far easier than AWS's solutions for deployment & CDN, and offers more features.
@ffxsam solution worked for me.
I'd add the following steps to ensure you're not getting a cached response:
- Invalidate the CloudFront cache for
index.htmlandservice-worker.jsfiles (see here). Otherwise you'll need to wait 24 hours from the latest cached request. - Clear the browser cache (here's how to do it in Chrome).
EDIT: as @lalzada pointed, this is just a solution for devs and/or known testers. Asking real users to clear their cache is not a good solution at all.
@gaguirre based on your step 2, would you ask all of your users to clear browser cache after you deploy a new build? not sure if this is the solution...
