Search code examples
angulariisprogressive-web-appsservice-workerangular-service-worker

Angular PWA service worker not refreshing offline when deployed to IIS


Basically I have the same issue as this unanswered question describes.

When I am serving our PWA with http-server, everything seems to run fine, but when I deploy it to our live environment which is a Windows Server with IIS it only runs fine online. When I go offline, I cannot refresh the page. The service worker returns status 504 and I can't figure out why.

I'm running out of ideas how to troubleshoot.

Are there any useful guides how to correctly setup Angular apps on IIS? (specifically PWAs with offline capability)

Does anybody have ideas what I could check e.g. in my HTTP headers?


Solution

  • 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.