Workbox Stale-while-revalidate strategy always returns response from network call instead of cache

638 Views Asked by At

I am using workbox-webpack-plugin, below is code in webpack config

new GenerateSW({
  runtimeCaching: [
    {
      urlPattern: new RegExp('^https://devapi\.mysite\.xyz/'),
      handler: 'staleWhileRevalidate',
      options: {
        cacheableResponse: {
            statuses: [200]
        }
      }
    }
  ]
})

Below is flow of stale while revalidate strategy as per google doc

Stale while revalidate flow - Google Doc

I am calling API from cross domain, what I observed is each time response is given back to UI not from cache but from network call response.

I am expecting when same API is called 2nd time, I should get response from cache and then cache should be updated from response of network call.

2

There are 2 best solutions below

0
On

I think all the info in this "Handle Third Party Requests" guide should help.

In particular, make sure that your remote server is using CORS, or else you'll get back a response that has a status of 0. You're explicitly configuring the cacheableResponse plugin to only cache responses with a status of 200.

0
On

For anyone stumbling upon this now, the correct snippet should be. Workbox listens to StaleWhileRevalidate not staleWhileRevalidate.

new GenerateSW({
  runtimeCaching: [
    {
      urlPattern: new RegExp('^https://devapi\.mysite\.xyz/'),
      handler: 'StaleWhileRevalidate',
      options: {
        cacheableResponse: {
            statuses: [200]
        }
      }
    }
  ]
})