Posts

Cloudflare Workers RPC

While prototyping some new features for this site, I stumbled upon some unusual code in a Durable Objects guide. Surprisingly, it covered functionalities I had not seen documented, at least not within the past couple of months.

I had no idea you could directly call methods on Durable Object stubs! This discovery eliminates the need for cumbersome request routing boilerplate, trpc, and the often unnecessary low-level decisions. Simply obtain a handle to your object and call methods on it. Amazing.

let stub = env.COUNTERS.get(id);
 
// Send a request to the Durable Object using RPC methods, then await its response.
let count = null;
switch (url.pathname) {
  case "/increment":
	count = await stub.increment();
	break;
  case "/decrement":
	count = await stub.decrement();
	break;
  case "/":
	// Serves the current value.
	count = await stub.getCounterValue();
	break;
  default:
	return new Response("Not found", { status: 404 });
}

Source: Cloudflare Docs

Its a Javascript System; I Know this!

It turns out I'm not too far behind the times, although I'm puzzled about how I missed this announcement from April: JavaScript Native RPC on Cloudflare (spoiler: this feature extends beyond just Durable Objects). I’m glad I discovered this when I did.