Cloudflare Durable Objects allow GitHub Pages users to expand a static website into a platform capable of consistent state, sessions, and coordinated logic. Many developers question how a static site like GitHub Pages can support real-time functions or data accuracy, and Durable Objects provide the missing building block that makes global coordination possible at the edge.
Setelah memahami KV Storage pada artikel sebelumnya, bagian ini menggali lebih dalam bagaimana Durable Objects memberikan konsistensi data, kemampuan multi-step operations, dan interaksi real-time yang stabil bahkan untuk situs yang di-host di GitHub Pages. Untuk memudahkan navigasi, daftar isi berikut merangkum seluruh pembahasan.
Mengenal Struktur Stateful Edge untuk GitHub Pages
- What Makes Durable Objects Different from KV Storage
- Why GitHub Pages Needs Durable Objects
- Setting Up Durable Objects for Your Worker
- Building a Consistent Global Counter
- Implementing a Lightweight Session System
- Adding Real-Time Interactions to a Static Site
- Cross-Region Coordination and Scaling
- Case Study Using Durable Objects with GitHub Pages
- Future Enhancements with DO and Worker AI
What Makes Durable Objects Different from KV Storage
Durable Objects differ from KV because they act as a single authoritative instance for any given key. While KV provides global distributed storage optimized for reads, Durable Objects provide strict consistency and deterministic behavior for operations such as counters, queues, sessions, chat rooms, or workflows.
When a Durable Object is accessed, Cloudflare ensures that only one instance handles requests for that specific ID. This guarantees atomic updates, making it suitable for tasks such as real-time editing, consistent increments, or multi-step transactions. KV Storage cannot guarantee immediate consistency, but Durable Objects do, making them ideal for features that require accuracy.
GitHub Pages does not have backend capabilities, but when paired with Durable Objects, it gains the ability to store logic that behaves like a small server. The code runs at the edge, is low-latency, and works seamlessly with Workers and KV, expanding what a static site can do.
Why GitHub Pages Needs Durable Objects
GitHub Pages users often want features that require synchronized state: visitor counters with exact accuracy, simple chat components, multiplayer interactions, form processing with validation, or real-time dashboards. Without server-side logic, this is impossible with GitHub Pages alone.
Durable Objects solve several limitations commonly found in static hosting:
- Consistent updates for multi-user interactions.
- Atomic sequences for processes that require strict order.
- Per-user or per-session storage for authentication-lite use cases.
- Long-lived state maintained across requests.
- Message passing for real-time interactions.
These features bridge the gap between static hosting and dynamic backends. Durable Objects essentially act like mini edge servers attached to a static site, eliminating the need for servers, databases, or complex architectures.
Setting Up Durable Objects for Your Worker
Setting up Durable Objects involves defining a class and binding it in the Worker configuration. Once defined, Cloudflare automatically manages the lifecycle, routing, and persistence for each object. Developers only need to write the logic for the object itself.
Berikut langkah mendasar untuk mengaktifkannya:
- Open the Cloudflare Dashboard and choose Workers & Pages.
- Create or edit your Worker.
- Open Durable Objects Bindings in the settings panel.
- Add a new binding and specify a name such as
SESSION_STORE. - Define your Durable Object class in your Worker script.
Contoh struktur paling sederhana terlihat seperti ini:
export class Counter {
constructor(state, env) {
this.state = state;
}
async fetch(request) {
let count = await this.state.storage.get("count") || 0;
count++;
await this.state.storage.put("count", count);
return new Response(JSON.stringify({ total: count }));
}
}
Durable Objects use per-instance storage that persists between requests. Each instance can store structured data and respond to requests with custom logic. GitHub Pages users can interact with these objects through simple API calls from their static JavaScript.
Building a Consistent Global Counter
One of the clearest demonstrations of Durable Objects is a strictly consistent counter. Unlike KV Storage, which is eventually consistent, a Durable Object ensures that increments are never duplicated or lost even if multiple visitors trigger the function simultaneously.
Here is a more complete implementation:
export class GlobalCounter {
constructor(state, env) {
this.state = state;
}
async fetch(request) {
const value = await this.state.storage.get("value") || 0;
const updated = value + 1;
await this.state.storage.put("value", updated);
return new Response(JSON.stringify({ value: updated }), {
headers: { "content-type": "application/json" }
});
}
}
This pattern works well for:
- Accurate page view counters.
- Total site-wide visitor counts.
- Limited access counters for downloads or protected resources.
GitHub Pages visitors will see updated values instantly. Integrating this logic into a static blog or landing page is straightforward using a client-side fetch call that displays the returned number.
Implementing a Lightweight Session System
Durable Objects are effective for creating small session systems where each user or device receives a unique session object. This can store until visitor preferences, login-lite identifiers, timestamps, or even small progress indicators.
A simple session Durable Object may look like this:
export class SessionObject {
constructor(state, env) {
this.state = state;
}
async fetch(request) {
let session = await this.state.storage.get("session") || {};
session.lastVisit = new Date().toISOString();
await this.state.storage.put("session", session);
return new Response(JSON.stringify(session), {
headers: { "content-type": "application/json" }
});
}
}
This enables GitHub Pages to offer features like remembering the last visit, storing UI preferences, saving progress, or tracking anonymous user journeys without requiring database servers. When paired with KV, sessions become powerful yet minimal.
Adding Real-Time Interactions to a Static Site
Real-time functionality is one of the strongest advantages of Durable Objects. They support WebSockets, enabling live interactions directly from GitHub Pages such as:
- Real-time chat rooms for documentation support.
- Live dashboards for analytics or counters.
- Shared editing sessions for collaborative notes.
- Instant alerts or notifications.
Here is a minimal WebSocket Durable Object handler:
export class ChatRoom {
constructor(state) {
this.state = state;
this.connections = [];
}
async fetch(request) {
const [client, server] = Object.values(new WebSocketPair());
this.connections.push(server);
server.accept();
server.addEventListener("message", msg => {
this.broadcast(msg.data);
});
return new Response(null, { status: 101, webSocket: client });
}
broadcast(message) {
for (const conn of this.connections) {
conn.send(message);
}
}
}
Visitors connecting from a static GitHub Pages site can join the chat room instantly. The Durable Object enforces strict ordering and consistency, guaranteeing that messages are processed in the exact order they are received.
Cross-Region Coordination and Scaling
Durable Objects run on Cloudflare’s global network but maintain a single instance per ID. Cloudflare automatically places the object near the geographic location that receives the most traffic. Requests from other regions are routed efficiently, ensuring minimal latency and guaranteed coordination.
This architecture offers predictable scaling and avoids the "split-brain" scenarios common with eventually consistent systems. For GitHub Pages projects that require message queues, locks, or flows with dependencies, Durable Objects provide the right tool.
Case Study Using Durable Objects with GitHub Pages
A developer created an interactive documentation website hosted on GitHub Pages. They wanted a real-time support chat without using third-party platforms. By using Durable Objects, they built a chat room that handled hundreds of simultaneous users, stored past messages, and synchronized notifications.
The front-end remained pure static HTML and JavaScript hosted on GitHub Pages. The Durable Object handled every message, timestamp, and storage event. Combined with KV Storage for history archival, the system performed efficiently under high global load.
This example demonstrates how Durable Objects enable practical, real-world dynamic behavior for static hosting environments that were traditionally limited.
Future Enhancements with DO and Worker AI
Durable Objects continue to evolve and integrate with Cloudflare’s new Worker AI platform. Future enhancements may include:
- AI-assisted chat bots running within the same Durable Object instance.
- Intelligent caching and prediction for GitHub Pages visitors.
- Local inference models for personalization.
- Improved consistency mechanisms for high-traffic DO applications.
On the next article, we will explore how Workers AI combined with Durable Objects can give GitHub Pages advanced personalization, local inference, and dynamic content generation entirely at the edge.