Bindings · Exercise 02
Call another Worker
Create a second Worker with no public URL and call a method on it from your first Worker through a service binding.
Paste this into your agent
Copied! Now paste it into your agent. No agent yet? Here's how to get one.
Call another Worker
On most platforms, one service calls another over the network: an internal hostname, an API key to prove who’s calling, and some network rule that hopefully keeps everyone else out. On Cloudflare, a Worker can call another Worker through a binding, like calling a function.
What you’ll build
A second Worker, the greeter, with a greet() method and no public URL at all. Your first Worker calls it through a service binding as env.GREETER.greet("you"), and the binding tells the greeter who’s calling.
Then you’ll check that nothing else can reach the greeter, and think about what that rules out.
Prerequisites
- You’ve completed Live objects and still have that Worker on disk.
A Worker you call like a function
The greeter exports a class with a method on it:
src/index.tsimport { WorkerEntrypoint } from "cloudflare:workers";
export default class extends WorkerEntrypoint<Env, { caller: string }> {
async greet(name: string) {
return `Hello, ${name}! (called by ${this.ctx.props.caller})`;
}
}
Your first Worker binds to it in cloudflare.config.ts, saying who’s calling with props:
cloudflare.config.tsenv: {
GREETER: bindings.worker({ worker: greeter, props: { caller: "my-worker" } }),
},
And calls it like a local async function. There’s no HTTP request to build, no hostname, and no key:
const message = await env.GREETER.greet("Ada");
This is RPC (remote procedure call): the greeter runs as its own Worker, but you call its methods as if they were yours.
Why it matters
-
No URL leads to the greeter. Say your Worker fetches a URL a user gives it, like an avatar image:
const avatar = await fetch(userSuppliedUrl);On a private network, an attacker could pass an internal hostname and make your server fetch something only it can see. That’s server-side request forgery (SSRF). Here there’s no URL to pass: only code that uses
env.GREETERcan reach the greeter. -
There’s no API key between the two Workers and no certificate to manage. The binding is the permission.
-
The greeter can trust
props. Only someone allowed to deploy the greeter can set them (docs), so they work as the caller’s identity without signatures.propscan also limit a binding to one thing, like a single document. -
One caveat: a Worker on your own domain, in front of an existing server, can reach that server with a plain
fetch()to the domain, skipping Cloudflare’s security settings. Theglobal_fetch_strictly_publiccompatibility flag turns that off. A workers.dev Worker has no server behind it. -
For private services outside Cloudflare, like an API in another cloud or on a home network, Workers VPC brings bindings there too. A VPC Service is a binding to one host and port in your private network, not open network access.