`Request` object passed through AutoRouter cannot be `fetch`ed in Cloudflare Workers
Describe the Issue
I have a cloudflare worker that intercepts some routes, and just forwards all other routes to the origin. I believe this worked when i wrote the code originally, however it seems to have started failing when i picked up the project again earlier today.
Example Router Code
import { AutoRouter, Router } from 'itty-router';
const router = AutoRouter();
router.all('*', async (req) => {
try {
return await fetch(req);
} catch (e) {
console.error(e);
return new Response('proxy request failed');
}
});
export default {
async fetch(request, env, ctx) {
const u = new URL(request.url);
u.host = 'example.com';
u.port = '';
u.protocol = 'https';
const changedRequest = new Request(u, request);
if (u.searchParams.get('skip')) {
console.log('fetching directly');
return await fetch(changedRequest);
}
console.log('fetching through itty-router');
return router.fetch(changedRequest, env, ctx);
}
};
Request Details
GET http://localhost:8787 GET http://localhost:8787?skip=true
Steps to Reproduce
The minimal example just proxies all requests to example.com. If you start this in wrangler and invoke http://localhost:8787?skip=true it works fine. (This skips itty-router and just forwards the request directly). If you do not pass skip=true by just invoking http://localhost:8787 then it will fail with TypeError: Invalid URL: [object Request].
If you switch to the normal Router then it also works fine.
Expected Behavior
Cloudflare forwards the request without issues.
Actual Behavior
TypeError: Invalid URL: [object Request] (In the minimal example, compatibility_date="2024-12-30")
or
TypeError: Fetch API cannot load: [object Object] (In my original code, compatibility_date="2023-09-18")
Environment (please complete the following information):
- Environment: Cloudflare Workers
- itty-router Version: 5.0.18
- Other Relevant Libraries and their versions:
- Wrangler: 3.99.0
Additional Context
The issue seems to not occur when using Router directly. Tracing the issue this seems to be caused by withParams wrapping the request object in a Proxy, which Cloudflare cannot handle.
As a workaround i can initialize a new request object and copy over relevant properties, however this is a bit of a wack-a-mole as i have to make sure to do it in all places i fall back to just forwarding the original request.