© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
Cloudflare DevelopersCD
Cloudflare Developers•3y ago
romain05.c

Cache from worker not working properly

We did a cache middleware which must store the previous response.
The key is based on the url and we add country, device, displayMode etc on a query parameter.
It is not working properly, I mean it work only if le worker is being called by the same client(without hard refresh). I know the cached is not shared globally but what can we do to make it work when request hit the same datacenter from another clients?

  const key = country + '#' + displayMode.mode + '#' + device;
  const cache = caches.default;
  const reqUrl = new URL(context.req.url);
  reqUrl.searchParams.set('cache', key);

  let response = await cache.match(reqUrl.toString());
  if (!response) {
    await next();
    response = context.res.clone();
    const newResponse = new Response(response.body, response);
    newResponse.headers.append('Cache-Control', context.env.CACHE_CONTROL);

    console.log("Caching:::", reqUrl.toString());
    context.executionCtx.waitUntil(cache.put(reqUrl.toString(), newResponse))
  } else {
    console.log("Response from cache:::", reqUrl.toString())
    return response;
  }
  const key = country + '#' + displayMode.mode + '#' + device;
  const cache = caches.default;
  const reqUrl = new URL(context.req.url);
  reqUrl.searchParams.set('cache', key);

  let response = await cache.match(reqUrl.toString());
  if (!response) {
    await next();
    response = context.res.clone();
    const newResponse = new Response(response.body, response);
    newResponse.headers.append('Cache-Control', context.env.CACHE_CONTROL);

    console.log("Caching:::", reqUrl.toString());
    context.executionCtx.waitUntil(cache.put(reqUrl.toString(), newResponse))
  } else {
    console.log("Response from cache:::", reqUrl.toString())
    return response;
  }
Cloudflare Developers banner
Cloudflare DevelopersJoin
Welcome to the official Cloudflare Developers server. Here you can ask for help and stay updated with the latest news
85,042Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

cache worker request not working?
Cloudflare DevelopersCDCloudflare Developers / workers-and-pages-help
16mo ago
Bypassing cache from worker fetch
Cloudflare DevelopersCDCloudflare Developers / workers-and-pages-help
10mo ago
Cloudflare worker Cache not work
Cloudflare DevelopersCDCloudflare Developers / workers-and-pages-help
2y ago