HBForge/Examples
13 · Integrations

Cloudflare Durable Objects

Stateful primitives on the edge. c.env exposes the binding; the Durable Object class exports next to the app.

forge/serverCF Workers
Code
cloudflare-durable-objects.js
import { WebApp } from class="tk-str">'@hyperbridge/forge/server';

const app = new WebApp();

app.get(class="tk-str">'/counter', async (c) => {
  const id  = c.env.COUNTER.idFromName(class="tk-str">'global');
  const obj = c.env.COUNTER.get(id);
  return obj.fetch(new Request(class="tk-str">'http:class="tk-cm">//x/inc'));
});

export class Counter {
  constructor(state) { this.state = state; }
  async fetch(req) {
    let n = (await this.state.storage.get(class="tk-str">'n')) ?? 0;
    n++;
    await this.state.storage.put(class="tk-str">'n', n);
    return Response.json({ n });
  }
}

export default app;
How it works

WebApp is just a Fetch-API handler — export it as the default and Cloudflare Workers runs it directly. No adapter shim.

Durable Objects give you single-instance, strongly-consistent state — perfect for game lobbies, rate limiters, real-time presence, collaborative documents.

c.env.COUNTER is the binding declared in wrangler.toml. Every request that should hit the same DO uses idFromName(stableKey).

Try it
Quickstart
wrangler dev → curl http://localhost:8787/counter
Related modules