Search code examples
angularprogressive-web-appsangular-service-workercaching-strategy

Angular freshness strategy fetches data also from cache


On Angular docs the service worker freshness strategy is described as following:

freshness optimizes for currency of data, preferentially fetching requested data from the network. Only if the network times out, according to timeout, does the request fall back to the cache. This is useful for resources that change frequently; for example, account balances.

I implemented this strategy in my solution:

// ngsw-config.json

"dataGroups": [{
    "name": "jokes-cache",
    "urls": [ "https://icanhazdadjoke.com/" ],
    "cacheConfig": {
      "strategy": "performance",
      "maxSize": 5,
      "maxAge": "1d"
    }
  },
  {
    "name": "stocks-cache",
    "urls": [ "https://api.worldtradingdata.com/api/v1/stock" ],
    "cacheConfig": {
      "strategy": "freshness",
      "maxSize": 10,
      "maxAge": "1d",
      "timeout": "5s"
    }
  }]

But when I check the Network tab of the DevTools, I can see that not only the network call is triggered, but also the local cache is accessed:

enter image description here

I would expect to see only the network call for the "stock" endpoint and no access to the cache (the response comes way before the 5 secs timeout).


Solution

  • The screenshot looks correct. The gear icon near the second request does not mean accessing the cache - it just means that this network request was performed from the service worker (which is intended behavior in that case).