Caching by device using same URL with worker

Im very new to workers, I want to serve cache according to the device

  • a request for a mobile version of could be cached under
  • a desktop version could be cached under

I logged into my Cloudflare account and created a subdomain for my worker, then I created the worker, this is how the code of my worker looks:

async function run(event) {
  const { request } = event;

  const cache = caches.default;

  // Read the user agent of the request
  const ua = request.headers.get('user-agent');
  let uaValue;

  if (ua.match(/mobile/i)) {
    uaValue = 'mobile';
  } else {
    uaValue = 'desktop';

  // Construct a new response object which distinguishes the cache key by device
  // type.
  const url = new URL(request.url);
  url.searchParams.set('ua', uaValue);
  const newRequest = new Request(url, request);

  let response = await cache.match(newRequest);
  if (!response) {
    // Use the original request object when fetching the response from the
    // server to avoid passing on the query parameters to our backend.
    response = await fetch(request);

    // Store the cached response with our extended query parameters.
    event.waitUntil(cache.put(newRequest, response.clone()));

  return response;

addEventListener('fetch', (event) => {

So Im adding the url params so I can cache different versions of my site according to the device.

I created the route for my worker this way:

It should work this way, shouldn’t it? I don’t know what’s missing, my pages aren’t yet cached accordingly, so I don’t know what to do now. I have some page rules as well but I just have some cache bypass rules for certain pages, that’s it…

Is something wrong with my worker?

Hi made it work, it seems it was an issue with the http control cache headers of my web server, I added

response = await fetch(request, { cf: { cacheTtl: 14400 } });

to overwrite that and now it is caching okey, but still can’t make it work to make the different caches for my mobile and desktop versions work, it still caches eveyrything the same, I tested the User Agent strings and it correctly detects desktop and mobiel, so don’t understand why it is still caching everything the same…

1 Like

Hi there - I have the same issue with cache by user-agent - seems like it sometimes works and sometimes not.

Please check my solution to detect mobile by user agent it based on WordPress WP_IS_MOBILE()

let uaValue = ‘desktop’;

** if (/Mobile|Android|Silk|Kindle|BlackBerry|Opera Mini|Opera Mobi/i.test(ua)) {**
** uaValue = ‘mobile’;**
** }**
** url.searchParams.set(‘ua’, uaValue);**