Skip to content

Unable to Clear Cached Data in Angular-Generated Service Worker #58733

@mehranmb78

Description

@mehranmb78

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

service-worker

Is this a regression?

No

Description

I am using the Angular Service Worker, and it works well overall. However, I encountered a potential data leak issue when caching API responses. Here’s the scenario:

If I cache an API response (e.g., abc.com/api/posts) for User A, then log out and log in as User B, and switch to offline mode before fetching the API for User B, I can still see the cached data belonging to User A. This is a significant security concern, as it exposes sensitive data across user sessions.

To address this issue, I decided to implement a custom service worker to extend the functionality of Angular’s generated service worker. My custom implementation looks like this:

importScripts('./ngsw-worker.js');

self.addEventListener('message', async (event) => {
    const cacheNames = await self.caches.keys();
    for (const name of cacheNames) {
        await self.caches.delete(name);
    }
});

With this approach, I expect that sending a message (e.g., after logging out) will clear all cached data from the browser's cache storage:

navigator.serviceWorker.controller.postMessage({
    type: 'CLEAR_CACHE',
});

While this solution successfully clears the visible data in the browser’s cache storage (verified via DevTools), an issue persists: if I refresh the page and switch to offline mode, the previously cached data is still accessible. This suggests that Angular’s ngsw-worker.js maintains an internal cache that I cannot access or clear using my current implementation.

Please provide a link to a minimal reproduction of the bug

No response

Please provide the exception or error you saw


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

Angular CLI: 17.2.3
Node: 20.10.0
Package Manager: npm 10.2.3
OS: Mac os

Angular: 17.2.3
... animations, common, compiler, compiler-cli, core, forms
... platform-browser, platform-browser-dynamic, router

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1702.3
@angular-devkit/build-angular   17.2.3
@angular-devkit/core            17.2.3
@angular-devkit/schematics      17.2.3
@angular/cli                    17.2.3
@schematics/angular             17.2.3
rxjs                            7.5.6
typescript                      5.3.3
zone.js                         0.14.4

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