Angular PWA on a NestJS server crashes after new deployment

328 views Asked by At

I am running an Angular PWA (version 11) on a NestJS (version 7) server. After every new deployment, the PWA crashes because the browser tries to load a JavaScript file which is not there anymore and the server redirects to the root site (html):

main.945bce5e14ef8a6c0362.js:1 Uncaught SyntaxError: Unexpected token '<'

The app module (app.module.ts) is configured as follows:

import { join } from 'path';

import { Module } from '@nestjs/common';
import { ServeStaticModule } from '@nestjs/serve-static';

import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  imports: [
    ServeStaticModule.forRoot({
      serveStaticOptions: {
        etag: false,
        setHeaders: (res, path) => {
          if (path.includes('ngsw.json')) {
            res.set('Cache-Control', 'no-cache, no-store, must-revalidate');
          }
        }
      },
      rootPath: join(__dirname, '..', 'pwa'),
      exclude: ['/api*']
    })
  ],
  controllers: [AppController],
  providers: [AppService]
})
export class AppModule {}

Any suggestions? Thank you in advance.

1

There are 1 answers

0
BingBong On

I'm gonna show you how I use my service worker which is working, and you can test it and see if it does fix your problem.

This is how you import the service worker:

imports: [
  ServiceWorkerModule.register('/ngsw-worker.js', { enabled: environment.production })
]

You should use this in your app.component to test that the browser has service worker implemented:

public ngOnInit(): void {
  if (this.swUpdate.isEnabled) {
    this.swUpdate.available.subscribe(() => {
      if (confirm('Nouvelle version disponible')) {
        window.location.reload();
      }
    });
  }
}

This is what your service worker should look like:

{
  "index": "/index.html",
  "assetsGroups": [
    {
      "name": "App Name",
      "installMode": "prefetch",
      "ressources": {
        "files": [
          "/favicon.ico",
          "/index.html"
        ],
        "versionedFile": [
          "/*.bundle.css",
          "/*.bundle.js",
          "/*.chunk.js"
        ]
      }
    },
    {
      "name": "assets",
      "installMode": "lazy",
      "updateMode": "prefetch",
      "ressources": {
        "files": [
          "assets/**"
        ]
      }
    }
  ],
  "dataGroups": [
    {
      "name": "example-api",
      "urls": [
        "/api/example"
      ],
      "cacheConfig": {
        "strategy": "freshness",
        "timeout": "10s",
        "maxAge": "1d",
        "maxSize": 100
      }
    }
  ]
}