Modify request before calling other worker on spec...
# workers-help
m
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
Copy code
ts
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
Copy code
ts
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?
k
env.BINDING.fetch("http://service/edge/v1", request)
m
Cool stuff! Works perfectly!
Couldn't find it anywhere 😐
k
The
fetch()
API looks like this:
Copy code
ts
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...
Copy code
js
const url = new URL(request.url);
url.pathname = "/edge/v1"

await fetch(url, request);
etc
m
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 😋