Skip to content

Angular PWA and offline server #51337

@MutazNawas

Description

@MutazNawas

Which @angular/* package(s) are the source of the bug?

service-worker

Is this a regression?

Yes

Description

I utilize the PWA functionality to enable offline capabilities for my application. This involves executing the command ng add @angular/pwa. Initially, everything functions as intended. However, upon testing a scenario where the server experiences an outage or is offline, I observed that the cache storage is being cleared and the service worker is removed.

It's worth noting that there are no problems when the client is in an offline state. After investigating the ngsw-worker.js file, I identified a specific code segment responsible for triggering this cache clearance. The code is within the fetchLatestManifest function:

async fetchLatestManifest(ignoreOfflineError = false) {
  const res = await this.safeFetch(this.adapter.newRequest("ngsw.json?ngsw-cache-bust=" + Math.random()));
  if (!res.ok) {
    if (res.status === 404) {
      await this.deleteAllCaches();
      await this.scope.registration.unregister();
    } else if ((res.status === 503 || res.status === 504) && ignoreOfflineError) {
      return null;
    }
    throw new Error(`Manifest fetch failed! (status: ${res.status})`);
  }
  this.lastUpdateCheck = this.adapter.time;
  return res.json();
}

This behavior seems counterintuitive, as cache deletion shouldn't occur when the server is offline. Ideally, the service worker should cache the ngsw.json and rely on it, rather than deleting caches when the server experiences downtime. I'm seeking advice on potential solutions to this issue. Should I modify the code to resolve this problem? If so, what changes are recommended to ensure caches are retained even when the server is offline?

Please provide a link to a minimal reproduction of the bug

No response

Please provide the exception or error you saw

No response

Please provide the environment you discovered this bug in (run ng version)

No response

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: service-workerIssues related to the @angular/service-worker package

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions