♻️(service-worker) improve SW registration and update handling

It is apparently a bad practice to add the version
number to the service worker file name.
This prevents the browser from properly updating
the service worker when a new version is available.

We improve the update handling by a more usual
pattern.
This commit is contained in:
Anthony LC
2025-10-09 15:41:11 +02:00
parent 8023720da3
commit af01c6e466
3 changed files with 9 additions and 8 deletions

View File

@@ -30,6 +30,7 @@ and this project adheres to
- ♿ add h1 for SR on 40X pages and remove alt texts #1438
- ♿ update labels and shared document icon accessibility #1442
- 🍱(frontend) Fonts GDPR compliants #1453
- ♻️(service-worker) improve SW registration and update handling #1473
### Fixed

View File

@@ -11,7 +11,6 @@ const TestComponent = () => {
describe('useSWRegister', () => {
it('checks service-worker is register', () => {
process.env.NEXT_PUBLIC_BUILD_ID = '123456';
vi.spyOn(console, 'error').mockImplementation(() => {});
const registerSpy = vi.fn();
@@ -35,7 +34,7 @@ describe('useSWRegister', () => {
render(<TestComponent />);
expect(registerSpy).toHaveBeenCalledWith('/service-worker.js?v=123456');
expect(registerSpy).toHaveBeenCalledWith('/service-worker.js');
expect(addEventListenerSpy).toHaveBeenCalledWith(
'controllerchange',
expect.any(Function),
@@ -44,7 +43,6 @@ describe('useSWRegister', () => {
it('checks service-worker is not register', () => {
process.env.NEXT_PUBLIC_SW_DEACTIVATED = 'true';
process.env.NEXT_PUBLIC_BUILD_ID = '123456';
const registerSpy = vi.fn();
registerSpy.mockImplementation(
@@ -62,6 +60,6 @@ describe('useSWRegister', () => {
render(<TestComponent />);
expect(registerSpy).not.toHaveBeenCalledWith('/service-worker.js?v=123456');
expect(registerSpy).not.toHaveBeenCalledWith('/service-worker.js');
});
});

View File

@@ -7,7 +7,7 @@ export const useSWRegister = () => {
process.env.NEXT_PUBLIC_SW_DEACTIVATED !== 'true'
) {
navigator.serviceWorker
.register(`/service-worker.js?v=${process.env.NEXT_PUBLIC_BUILD_ID}`)
.register(`/service-worker.js`)
.then((registration) => {
registration.onupdatefound = () => {
const newWorker = registration.installing;
@@ -29,11 +29,13 @@ export const useSWRegister = () => {
console.error('Service worker registration failed:', err);
});
const currentController = navigator.serviceWorker.controller;
let refreshing = false;
const onControllerChange = () => {
if (currentController) {
window.location.reload();
if (refreshing) {
return;
}
refreshing = true;
window.location.reload();
};
navigator.serviceWorker.addEventListener(
'controllerchange',