4

Could anyone share some guidance into how to cache a call in the browser and have it last 5 minutes, 30 seconds, really anytime at all?

I'm having some real difficulties with this.

This works but can't figure out how to make it expire

fetch(
    '/get/id',
    {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' },
        cache: 'force-cache'
    }
);

This doesn't work at all

fetch(
    '/get/id',
    {
        method: 'GET',
        headers: { 'Content-Type': 'application/json', 'Cache-Control': 'max-age=30' },
    }
);
bryan
  • 8,879
  • 18
  • 83
  • 166
  • You would need to update the server to include `Cache-Control` in the response header. If you don't control the server, your only option is to implement caching yourself in code. – kkkkkkk Jul 03 '19 at 03:44

1 Answers1

0

Cache-Control is an HTTP cache header comprised of a set of directives that allow you to define when/how a response should be cached and for how long. You can configure your server to attach the Cache-Control header in the response, specifying which directives to use.

For this cache control to need to update the server to include the cache control in response, like below where the server specifies the cache control type (public) and max age of the response for the client. enter image description here

Other option, is to implement your own caching mechanism on client side, which expires in 5 min. Below is the code which implements the cache fetch call with the session storage as cache storage and 5 min expiry, invalidates itself if stale.

https://github.com/abhishekasana/jsDevelopCell/blob/master/cached_fetch.js

abhishek kasana
  • 1,462
  • 12
  • 14