Problem

After some crucial changes in the service worker and message payload simultaneously, it may become difficult to make it compatible in both ways.

Solution

The latest service worker should always be able to handle both old and new message payloads. While following this rule, the only problem we need to address is to force all subscribed users to update their service worker, otherwise they will stuck in the incompatible state.

Service workers prior to some old (68 chrome) versions were not able to automatically update service worker with an HTTP request.

This ability was introduced later and is heavily dependent on:

  • Cache-Control headers (max-age)
  • updateViaCache option in the service worker registration

There is a very good article about it - https://developer.chrome.com/blog/fresher-sw

Since service workers are already injected into user’s browsers, we can’t force them to update with an ‘updateViaCache’ option (it will only affect new users).

The only way to force update is to add Cache-Control: max-age=0 to response headers. All our static files are served from S3 and being cached by CloudFront. To add this header we need to perform two steps:

  • Add Cache-Control: max-age=0 to our static files in S3 (select files, Actions Change metadata Cache-Control)
  • Invalidate CloudFront cache (select distribution, Invalidations Create invalidation)