Unable to fetch with workers

I have the following worker deployed:

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

async function handleRequest(request) {
  return fetch("http://test.example.com:9000")
}

Note: The actual domain is not example.com, I am just using it for illustrative purposes.

test.example.com:9000 is not served over https and is running on a vps that I control. The example.com domain is pointed to Cloudflare, and the test.example.com has an A record pointing to the IP address of the vps with proxying (orange cloud) turned off.

Using the browser on my own machine, I am able to visit http://test.example.com:9000 successfully. I am also able to visit it using the ip address of the server: http://192.168.1.1:9000 (note: this is not the actual ip, it’s just for illustrative purposes).

However, if I use fetch in my worker to fetch the ip address, it returns the 1003 error code, saying that it can’t fetch from the ip address. Is there any technical reason why a worker cannot fetch from an IP address?

If I use fetch in my worker to fetch from http://test.example.com:9000, it times out and I get a http 522 error.

Any ideas why this is happening?

Non-standard ports (i.e 9000) are not supported with fetch().

It will fetch on the standard port for that scheme - so in your case, it’ll be fetching test.example.com on port 80.

Right, that makes sense. It does seem like an arbitrary limitation though.

1 Like

You can actually make requests to non-standard ports if the Worker is running on the same zone as the target domain. So if your Worker runs on worker.example.com, you can make subrequests to origin.example.com:9000 but not origin.example.net:9000.

It is for security reasons. People often whitelist Cloudflare IPs - who knows what kind of unsecured services they run on non-standard ports.

2 Likes

TIL - guess I better add that to my docs issue :face_with_spiral_eyes:

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.