Worker perfect in Preview but not live even with proper Route


#1

First time using Cloudflare Workers :slight_smile:

Everything looks great in the Worker Editor Preview tab!

For some reason though, I’m not seeing these changes live, even though I clicked “Deploy” and set up a Route (and I tried variations on Routes to make sure I wasn’t missing something).

Currently my route is of the form (I could have made it more specific, since I’m targeting a directory, but while troubleshooting I generalized it to rule out problems here with Routes):

*tld.tld/*

I believe that Route should match everything, be it http or https, www. or no subdomain, and anything at all inside (including longer paths like tld.tld/path1/page.html and tld.tld/page.html).

Everything works so perfectly in Preview, that I was surprised it didn’t just magically work in my browsers live! I’ve not used Cloudflare Workers before, but I use Page Rules frequently, and they’ve always just worked, when properly configured.

What am I missing here?

For reference, here is an (anonymized) version of my Worker script:

addEventListener('fetch', event => {
  var url = new URL(event.request.url);
  if (url.pathname.startsWith('/pages/')) {
    handleBlog(event, url);
  } else {
    event.respondWith(fetch(event.request));
  }
})

async function handleBlog(event, url) {
  var destUrl = 'https://newsub.newhost.com';
  var originUrl = url.toString()
    .replace('http://oldhost.com/pages', destUrl)
    .replace('http://www.oldhost.com/pages', destUrl)
    .replace('https://oldhost.com/pages', destUrl)
    .replace('https://www.oldhost.com/pages', destUrl);
  event.respondWith(fetch(originUrl));
}

#2

Never mind, it was simply some caching going on with my internet provider. Once I switched to a different ISP connection, it all worked perfectly :slight_smile:


#3

Glad you figured it out!

By the way, I would recommend avoiding calling event.respondWith() from within async functions. In the example you provided it works correctly because there are no awaits before the event.respondWith() call, but if you were to accidentally place one above that call, the script would break.

It’s generally best to follow a pattern that calls event.respondWith() right up front, like this:

addEventListener("fetch", event => {
  event.respondWith(handle(event.request))
})

async function handle(request) {
  // All of your logic ...
}

That way, you can refactor asynchronous code inside of handle() all you want without worrying about this issue.