Angular Service Worker : Refresh of application being deployed throws a 504 error

905 Views Asked by At
  • I build my angular 8 project using ng build --prod

  • Serve it from /dist folder using http-server ( and eventually stop it and the app still works served via the service worker)

  • the project registers its service worker

  • I am able to navigate through the routes which I have pre-fetched and loaded from the chunks

  • I refresh the routes, it works as expected.

  • However when I do the same to the solution which has been deployed to the server ( IIS ) it throws a 504 error i.e. This page isn’t working ______ took too long to respond. HTTP ERROR 504

** - although the base route works (even on refresh ) but the child route doesn't (able to navigate but on reload it throws a 504) and in the networks tab I see a failed status **

Also, the base href for our application is configurable based on the different environments which we are using. even though we mention the scope as the current base href and the start url as '/index.html' OR './' OR '/', The issue seems to persist.

Is it IIS's behavior or the manifest.json file seems to be the culprit or anything else I need to configure to work this set up?

1

There are 1 best solutions below

0
On

I had the same issue here a while back and was able to resolve it for me. It has been working fine since, so I decided to share it here, too. Here's my answer on my post:

So apparently my issue didn't have anything to do with my IIS configuration. I still can't explain why it worked on http-server, but now I got it working on IIS, too.

After a lot of research and unsuccessful experiments, I tried to observe, what exactly ngsw-worker.js does that leads to this error. After putting some breakpoints and finding new keywords to search for I stumbled across this GitHub issue which led me to this much discussed issue. In one of his comments the user jackkoppa mentioned his StackOverflow Question where he found a workaround to fix such an issue.

Basically, I just added his script to our project and added the command for it to our project.json.

Here are the steps he describes:

To use the workaround: (Angular 5, tested w/ Angular 5.2.1)

  1. npm install replace-in-file --save-dev
  2. Include this script in your app, e.g. at build/fix-sw.js
  3. In your package.json:
"scripts": {
    ...
    "sw-build": "ng build --prod && node build/fix-sw",   
    "sw-build-live": ng build --prod --base-href https://your-url.com/ && node build/fix-sw"
    ...
}
  1. To run locally
npm run sw-build
cd dist
http-server -p 8080
  1. And to prepare a build for your live URL, before sending to a server (e.g. with angular-cli-ghpages) npm run
sw-build-live

After adding the script, my Angular app finally behaves as intended.

We don't use base-href in our case, so all it does for us, is comment out every time the service worker would write EXISTING_CLIENTS_ONLY to its state.