Gain an Understanding of a "Self Referencing" Worker (Why Does this Work?)

I have a worker that does two things:

  1. Serves a subdomain as a subdirectory
  2. Redirects the subdomain to the subdirectory

This worker is available on two different routes

  1. Every path on the subdomain (https://blog.example.com/*)
  2. The blog subdirectory (https://www.example.com/blog*)

Somehow this works, but I don’t understand how this doesn’t cause an infinite loop. Why doesn’t this happen:

  1. I go to https://blog.example.com/blog (Worker runs and redirects me to Step 2)
  2. I get redirected to https://www.example.com/blog (Worker runs and requests the URL from Step 1)
  3. https://blog.example.com/blog is requested from Step 2 and the cycle repeats…

The thing is this doesn’t happen. It works fine. The worker is called twice, but after Step 2 it doesn’t go back to Step 3 – it somehow retrieves the subdomain without getting redirected. HOW.

I’m curious because as soon as I separate the logic into different Workers, I start getting an error 1019 which is “A Cloudflare Worker script recursively references itself.”

I need to separate the logic, but thinking it’ll help to understand why it works if it’s in the same worker to begin with.

Thanks so much I’m banging my head over hear.

Attaching screenshots for verification (I only changed the domain). I can only upload one image so here’s a sloppy collage :slight_smile: containing…

  • The single Worker’s code
  • The routes the worker is on
  • After loading Step 1, the two logs that show up
  • The first log expanded
  • The second log expanded