Search code examples
javascriptcachingservice-worker

Is it a good idea to use service worker to cache app requests and periodically refetching them?


I have a very slow API which I don't have access to change.

it has endpoints like /data?param1=option1&param2=option2

is it a good idea to create a service worker, which will save responses of the requests as cache and periodically refetch them(with jwt for authentication)(data changes pretty rarely, like once a week)? Is there any caveats?


Solution

  • Nope, that's totally fine.

    Probably the most important problem you will encounter is, as usually with caching, cache invalidation process.

    In your case, if you strongly decide to cache responses for a limited amount of time without additional conditions, you probably can add a header to every cached response, which will hold a caching date.

    Here's the article that explains the idea: How to set an expiration date for items in a service worker cache

    In a nutshell, when you intercept a response, you unpack it, add a header with a current timestamp inside, then put in into the SW cache. Next, every time you intercept the request to the same endpoint, you get the response from the cache and check the timestamp in the header you set. Then return the cached response or refetch data, depending on the check result.


    Another one thing to think about is the refetching strategy. You see, there are different approaches here:

    1. Cache-First. It means that you always return the cached data to your app, and then go for refetch. This way even when it's time to show fresh data, your user will get the data from cache, and only next time they will get the fresh data. Not so pleasant for users, but this way the loading time will always be blazing fast (except the first visit, of course).

    2. Network-First. Vice versa. This way users will wait for the fresh data, but it always will be actual.

    3. Stale-While-Revalidate. Nice but header to implement. You return cached value, then, when SW fetched the fresh one, you trigger your app to rerender the page.

    Here's a nice tutorial explaining how all this caching works: Service workers tutorial