Durable Counter
Reference implementation for Durable Objects - a globally consistent counter with persistent edge state
A minimal reference for Durable Objects: a single Counter class with persistent storage, exposed via HTTP routes. Use this pattern when you need strongly consistent state at the edge (rate limits, sessions, coordination).
API Endpoints
GET /counter
Returns the current counter value.
Example Request
curl "https://your-worker.workers.dev/counter"Example Response
{ "value": 42 }POST /counter/increment
Increments the counter by 1.
curl -X POST "https://your-worker.workers.dev/counter/increment"POST /counter/reset
Resets the counter to 0.
curl -X POST "https://your-worker.workers.dev/counter/reset"Use Cases
- Learn how to define and export a Durable Object class
- Shared counters or rate limiters across all edge locations
- Starting point for session storage or real-time coordination
- Understanding
idFromName()for addressing a single global object
Deployment
Test the API
curl "https://your-worker.workers.dev/counter"
curl -X POST "https://your-worker.workers.dev/counter/increment"Local Development
cd apps/experiments/durable-counter
npm install
npm run devConfiguration
wrangler.json declares:
- Durable Object binding
COUNTER→ classCounter - Migration
v1registering theCounterclass
Cloudflare Features Used
- Durable Objects - strongly consistent state and storage
- Workers - HTTP routes that call into the DO stub