Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best service worker strategy for create-react-app?

Every code update to the production build shows a white screen to the user until they refresh the page. What is the best service worker strategy for code updates to be pushed seamlessly to the user? (no page refresh or cache clearing necessary)

The default service worker behavior is not ideal. It seems that every production code update causes the browser to show a white screen until the user manually refreshes the page. I understand this may require something along the lines of sw-precache and implementing workbox for custom service worker functionality - that is all fine, and I've tried that out and have gotten those libraries running and working to the point that It still mimics the exact same behavior (so I think the project is essentially ready for the correct service worker to be implemented without ejecting). However, I'm still lost as to what is the best caching strategies/service worker to use to achieve my desired result?

like image 607
Timothy Wilburn Avatar asked Oct 28 '25 14:10

Timothy Wilburn


1 Answers

Heyy Timothy!

I think you already found the answer to your question by now. I hope this answer will help future developers in their journey.

The strategies you are referring to are called caching strategies. Here's a list of commonly used ones:

  • networkOnly – only fetch from the network
  • cacheOnly – only fetch from cache
  • fastest – fetch from both, and respond with whichever comes first
  • cacheFirst – fetch from the cache, but also fetch from network and update cache

By default, CRA's service worker uses the cache-first strategy.

In your case, you have the possibility to choose between 2 strategies:

  • networkOnly Strategy

Pros: Will always render the latest version of the app (No white screen)

Cons: This will cause the user to fetch the app from the network every time.

  • networkFirst Strategy

This strategy can be used in your case. You can set your SW to look out for a version update. If a new version is found, you can display a small toaster saying 'Hey there, a new version is available please click here to refresh'


You can also check the following links for more information:

  • https://serviceworke.rs/caching-strategies.html
  • https://blog.bitsrc.io/understanding-service-workers-and-caching-strategies-a6c1e1cbde03
  • https://medium.com/@glukmann/let-users-know-when-you-have-updated-your-service-worker-in-create-react-app-b0c2701995b3
like image 125
twixs Avatar answered Oct 30 '25 06:10

twixs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!