I have an Angular 16 webpage with a service worker. This page is served by a NGINX which is under my control. Recently I have noticed that when visiting the page, the browser shows the old version. I have to refresh the webpage to get the current version. When reopening the page after a while the old page is shown again.
I have tried to disable caching on the NGINX, but this does not work.
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri$args $uri$args/ /index.html;
expires off;
add_header Cache-Control "no-cache, no-store, must revalidate";
}
I have also tried to write an UpdateService to reload the page when an Update is available. But I guess it was too late.
@Injectable({
providedIn: 'root',
})
export class UpdateAppService {
constructor(swUpdate: SwUpdate) {
swUpdate.versionUpdates
.pipe(
tap(console.log),
filter((evt): evt is VersionReadyEvent => evt.type === 'VERSION_READY')
)
.subscribe((evt) => {
document.location.reload();
});
}
}
This my ngsw-config.json
{
"$schema": "../../node_modules/@angular/service-worker/config/schema.json",
"index": "/index.html",
"assetGroups": [
{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [
"/favicon.ico",
"/index.html",
"/manifest.webmanifest",
"/*.css",
"/*.js"
]
}
},
{
"name": "assets",
"installMode": "lazy",
"updateMode": "prefetch",
"resources": {
"files": [
"/assets/**",
"/*.(svg|cur|jpg|jpeg|png|apng|webp|avif|gif|otf|ttf|woff|woff2)"
]
}
}
]
}
I have no meta tags to prevent caching on the index.html
itself.
The url /ngsw/state
seems to show an error.
NGSW Debug Info:
Driver version: 16.1.8
Driver state: SAFE_MODE (Initialization failed due to error: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON)
Latest manifest hash: none
Last update check: 12s307u
=== Idle Task Queue ===
Last update tick: 12s30u
Last update run: 7s22u
Task queue:
Debug log:
It seems the NGINX config was the cause that the service worker was loading a wrong file. The service worker switched then to SAFE_MODE
.
I have swapped the config with the following code and now it is working.
server {
listen 80;
listen [::]:80;
server_name localhost;
#access_log /var/log/nginx/host.access.log main;
root /usr/share/nginx/html;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}