Cache fetch response


Let’s say I’d want to use the fetch some data from a random api. How could I cache the response so if there’s a fresh response it wouldn’t fetch it again. I’ve been testing for some time on a test website but it doesn’t seem like it’s working. I’ve been searching through various sites but couldn’t find a response that I need.

const fetch = require("node-fetch");

async function getData() {
    const api = '-';
    const response = await fetch(api);
    const data = await response.json();
    return data;

(async () => {

 let requiredData = await getData();


Could I get a link to a page explaining this in-depth?

const cache = {};

async function getData(url) {
  if (url in cache) {
    return cache[url];
  } else {
    const resp = await fetch(url);
    const data = await resp.json();
    cache[url] = data;
    return data;

Basically just that. You need some key to identify the request – I’ve just used whatever the URL string is here. If the data for that url has already been stored in the cache object, just return that. Else make the request, store the response data in the cache with a key of that url and then return it.

1 Like

Thanks, everything is clear now.

1 Like