Can I change the requested URL in a middleware?

I created a page middleware, and I'd like to update the requested URL from foo/bar to bim/bam/boum in the event object? Here's my skeleton code:
export const useBackendPathResolver = ({ forward }: MiddlewareInput) => {
return async (event: FetchEvent) => {

const pathname = new URL(event.request.url).pathname;
console.log("From middleware", pathname); // --> /foo/bar

// How can I change the requested URL?
// So that my route `routeData` func gets props.location == "/bim/bam/boum"

return forward(event);
};
};
export const useBackendPathResolver = ({ forward }: MiddlewareInput) => {
return async (event: FetchEvent) => {

const pathname = new URL(event.request.url).pathname;
console.log("From middleware", pathname); // --> /foo/bar

// How can I change the requested URL?
// So that my route `routeData` func gets props.location == "/bim/bam/boum"

return forward(event);
};
};
1 Reply
Jérémy
JérémyOP2y ago
So the answer was in fact pretty easy, the trick is to re-create a FetchEvent:
const url = new URL(
`/bim/bam/boum`,
"http://internal"
);
const request = new Request(url.href);

const fetchEvent: FetchEvent = {
request,
env: event.env, // Grab back previous env
};

return forward(fetchEvent);
const url = new URL(
`/bim/bam/boum`,
"http://internal"
);
const request = new Request(url.href);

const fetchEvent: FetchEvent = {
request,
env: event.env, // Grab back previous env
};

return forward(fetchEvent);
Hmm, it seems that nothing gets hydrated on the rendered page.
Want results from more Discord servers?
Add your server