How to modify the url of a request object in fetch API?

Viewed 1703

I am using Cloudflare worker which is triggered by HTTP requests. I want to take the incoming request, change the url but leave all other properties untouched, and then issue the request. The structure is loke the following:

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

async function handleRequest(request) {

  #change the value of request.url and then...

  return fetch(request)
    .then(response => {
        return response;
    });
}
2 Answers

To clone a Request object, but change the URL, you can do this:

new Request("https://example.com/the/new/url", originalRequest);

Try it in your browser console:

let originalRequest = new Request("https://example.com")
let newRequest = new Request("https://voxviva.app", originalRequest);

Inspect newRequest. You will not see the old URL anywhere.

You can do this:

async function handleRequest(request) {

  #change the value of request.url and then...

  return fetch({...request, url: "someUrl"})
    .then(response => {
        return response;
    });
}

This will overwrite the url with "someUrl" Hope this helps :)

Related