How to access environment variables in Cloudflare Workers when using RPC binding
I'm working with two separate Cloudflare Workers, where Worker A calls a function in Worker B via a binding (RPC). Worker B requires an environment variable to send an email, and this variable should be scoped to Worker B itself, so it doesn't depend on Worker A's environment.
Here's the relevant code for Worker B:
When I use HTTP with fetch in Worker A, it works fine:
However, if I want to call Worker B directly via an RPC-style binding (like
await c.env.WORKER_EMAIL.send(email, firstName)
), I run into issues with accessing the environment variable env.RESEND_API
directly in Worker B. It seems the environment is not properly scoped when using RPC and it stays undefined
Question: How can I pass the correct environment to Worker B's send function when using RPC? Or is there a better way to structure this to ensure Worker B can access its own environment variables independently of Worker A?
What am I missing here? Any guidance would be greatly appreciated!2 Replies
@Skye, thanks for pointing that out! While I used
this.env
within the fetch function to pass the env
parameter to the send function, it didn’t occur to me that I don’t actually need the env
parameter—I can simply declare it within the send function 🤦♀️ . I think I had a big mental block there. Thanks for helping me untangle it!If anyone is stumbling upon this when using TypeScript, just make sure to define your Env interface and then extend WorkerEntrypoint<Env>
this allows this.env to be visible by the ts compiler and to not cause any warnings in development.
this exists in other examples, but not in the RPC ones.