Modify request before calling other worker on specific URL

Is it possible to modify request before passing it to binding? Let's say I have code like this on top level worker that sits on https://example.com/edge/backporter
import { Router } from 'itty-router';
const router = Router();

router.get('/edge/backporter', async (request) => {
request.query = '?foobar' // modify request
// Set URL to specific URL in other worker
request.url = '/edge/v1' // Error, cannot set read-only property
return env.BINDING.fetch(request);
}
import { Router } from 'itty-router';
const router = Router();

router.get('/edge/backporter', async (request) => {
request.query = '?foobar' // modify request
// Set URL to specific URL in other worker
request.url = '/edge/v1' // Error, cannot set read-only property
return env.BINDING.fetch(request);
}
And on BINDING worker I have router that responds to certain URL only https://example.com/edge/v1
import { Router } from 'itty-router';
const router = Router();

router.get('/edge/v1', async (request) => { ... }
import { Router } from 'itty-router';
const router = Router();

router.get('/edge/v1', async (request) => { ... }
I'd like to make sure request from first worker ends up in /edge/v1, but it never does, since I can't change request URL, nor can I request.clone(), since then URL would match /edge/backporter and not /edge/v1 Is anything like this possible?
4 Replies
kian
kian5mo ago
env.BINDING.fetch("http://service/edge/v1", request)
McSneaky
McSneaky5mo ago
Cool stuff! Works perfectly! <:cavai_hearts:908519873188098118> Couldn't find it anywhere 😐
kian
kian5mo ago
The fetch() API looks like this:
fetch(
input: RequestInfo,
init?: RequestInit<RequestInitCfProperties>
): Promise<Response>;
fetch(
input: RequestInfo,
init?: RequestInit<RequestInitCfProperties>
): Promise<Response>;
RequestInfo is either a Request, a string or a URL. In this case, we pass a string (http://service/edge/v1) and pass the original Request to the optional init property to carry over everything in RequestInit, like method/headers/body/cf. You could also do...
const url = new URL(request.url);
url.pathname = "/edge/v1"

await fetch(url, request);
const url = new URL(request.url);
url.pathname = "/edge/v1"

await fetch(url, request);
etc
McSneaky
McSneaky5mo ago
Yeah, I tried to pass full URL, that didn't work, then found about service / worker binding, but all doc examples were just passing the same request or request.clone() Which made me think it's not possible to modify the request Replacing base URL (example.com) with service name is exactly the thing I was looking for 😋