Creating new request with URL alters behaviour

We’re seeing some strange behavior in our worker when attempting to modify the URL of a request.

When we simply create a new Request object, all works as expected:

let newRequest = new Request(request);
let response = await fetch(newRequest);

No issue here whatsoever, but as soon as we feed a URL object into the Request object (using the same URL from the request):

let requestUrl = new URL(request.url);
let newRequest = new Request(requestUrl , request);
let response = await fetch(newRequest);

Lots of javascript in our system suddenly errors, resources fail to load etc. We’ve proven it’s this simple change which is the cause of our problems, but we can’t understand why the above would make the request behave differently?

Does anyone know why creating a Request object with a URL parameter seems to change behavior?

According to the documentation at https://developers.cloudflare.com/workers/reference/apis/request/ you are not supposed to pass a URL object but only either another Request object or the URL as string.

So does this work?

let newRequest = new Request(request.url, request);
let response = await fetch(newRequest);

Problem is we need to change the hostname of the request, whilst keeping everything else.

In their example, they pass a URL and request object into the constructor:

const newRequest = new Request(url, new Request(request, newRequestInit))

That example would contradict Cloudflare’s own documentation.

Anyhow, have you tried the code mentioned earlier?

The code mentioned earlier is valid and works successfully, but it doesn’t change the request URL (it’s the hostname of the request we need to modify).

If we create a new URL object and feed it in, we hit the problems.

The code you posted didnt change the URL either. Simply pass the new URL - as mentioned - as string instead of as object.

We’ve tried passing the newUrl.toString(), but results in the exact same behavior as passing in the object.

In that case the type might not be the issue.

Can you post a fully working example? Also, which error messages?

Seems to work fine

https://cloudflareworkers.com/#9fda8697e888b2874f05418270d5078f:https://tutorial.cloudflareworkers.com

Thanks,

Feeding in a URL object changes something about the request (we can’t work out what though), but results in numerous errors afterwards.

Feeding in a string as the URL and a request object does finally appear to be behaving though, we scrapped the URL object entirely as suggested and just manipulated a string.

Really bizarre, no idea what causes the difference.

Cheers.

This topic was automatically closed after 14 days. New replies are no longer allowed.