Hi folks, I'm trying to speed run a

Hi folks, I'm trying to speed run a prototype with Workers on top of my existing local stack. Basically I want to simulate normal traffic serving, but only a subset of my traffic routes should go to Workers. Is there an off the shelf pattern I can use for doing this reverse proxy in front of my existing stack?
10 Replies
skgz
skgzOP4mo ago
(Again, this is against my localhost stack. A prod-like env will be another beast.)
Hard@Work
Hard@Work4mo ago
Maybe within the Worker, have something like this?
export default {
fetch(req, env, ctx) {
const shouldSendToWorkers = Math.random() > 0.5;
if(shouldSendToWorkers) {
return actualWorkerCode(req, env, ctx);
}
return fetch(req);
}
}
export default {
fetch(req, env, ctx) {
const shouldSendToWorkers = Math.random() > 0.5;
if(shouldSendToWorkers) {
return actualWorkerCode(req, env, ctx);
}
return fetch(req);
}
}
skgz
skgzOP4mo ago
Suppose I have my local stack running at the url: my-local.dev:1234 and I want the worker to handle: my-local.dev:1234/foo & my-local.dev:1234/bar And it should reverse proxy all other URLs. What would that config look like? Thanks btw!
Hard@Work
Hard@Work4mo ago
Are you using a Router already?
skgz
skgzOP4mo ago
Where "my-local.dev" is just a localhost mapped DNS record No, brand new to Cloudflare! We currently use Cloudfront, and I'll be testing out a switch to cloudflare if this is successful.
Hard@Work
Hard@Work4mo ago
Ok, so the naive way is to just check the path of the incoming request directly, like
export default {
fetch(req, env, ctx) {
const { pathname } = new URL(req.url);
if(pathname.startsWith("/foo") || pathname.startsWith("/bar")) {
return actualWorkerCode(req, env, ctx);
}
return fetch(req);
}
}
export default {
fetch(req, env, ctx) {
const { pathname } = new URL(req.url);
if(pathname.startsWith("/foo") || pathname.startsWith("/bar")) {
return actualWorkerCode(req, env, ctx);
}
return fetch(req);
}
}
This works for one or two routes, but doesn't scale very well It also sends stuff like /foobar to your Worker, which may not be what you want
skgz
skgzOP4mo ago
Where does the fetch call proxy to? Eg, if I have the worker listen on the 1234 port above, I'd need to map my local stack to 1235 (for example). Do I configure the upstream domain, or do I need to edit the req.url?
Hard@Work
Hard@Work4mo ago
I believe you can point it to a local service with --local-upstream
Hard@Work
Hard@Work4mo ago
Cloudflare Docs
Commands - Wrangler · Cloudflare Workers docs
Create, develop, and deploy your Cloudflare Workers with Wrangler commands.
skgz
skgzOP4mo ago
Thank you! I've got some stuff rolling. One more Q: If I want it to fetch some upstream data, how do I have it load that and cache it in the background? Eg, our build system generates a manifest that I'd like to cache locally (ideally I'd refresh this periodically).
Want results from more Discord servers?
Add your server