Durable Object Base Class
The DurableObject base class is an abstract class which all Durable Objects inherit from. This base class provides a set of optional methods, frequently referred to as handler methods, which can respond to events, for example a webSocketMessage when using the WebSocket Hibernation API. To provide a concrete example, here is a Durable Object MyDurableObject which extends DurableObject and implements the fetch handler to return "Hello, World!" to the calling Worker.
export class MyDurableObject extends DurableObject { constructor(ctx, env) { super(ctx, env); }
async fetch(request) { return new Response("Hello, World!"); }}export class MyDurableObject extends DurableObject { constructor(ctx: DurableObjectState, env: Env) { super(ctx, env); }
async fetch(request: Request) { return new Response("Hello, World!"); }}from workers import DurableObject, Response
class MyDurableObject(DurableObject): def __init__(self, ctx, env): super().__init__(ctx, env)
async def fetch(self, request): return Response("Hello, World!")-
fetch(request Request): Response | Promise<Response>-
Takes an HTTP Request ↗ and returns an HTTP Response ↗. This method allows the Durable Object to emulate an HTTP server where a Worker with a binding to that object is the client.
-
This method can be
async. -
Durable Objects support RPC calls as of compatibility date 2024-04-03. RPC methods are preferred over
fetch()when your application does not follow HTTP request/response flow.
-
requestRequest - the incoming HTTP request object.
- A Response or Promise<Response>.
export class MyDurableObject extends DurableObject { async fetch(request) { const url = new URL(request.url); if (url.pathname === "/hello") { return new Response("Hello, World!"); } return new Response("Not found", { status: 404 }); }}export class MyDurableObject extends DurableObject<Env> { async fetch(request: Request): Promise<Response> { const url = new URL(request.url); if (url.pathname === "/hello") { return new Response("Hello, World!"); } return new Response("Not found", { status: 404 }); }}-
alarm(alarmInfo? AlarmInvocationInfo): void | Promise<void>-
Called by the system when a scheduled alarm time is reached.
-
The
alarm()handler has guaranteed at-least-once execution and will be retried upon failure using exponential backoff, starting at two second delays for up to six retries. Retries will be performed if the method fails with an uncaught exception. -
This method can be
async. -
Refer to Alarms for more information.
-
alarmInfoAlarmInvocationInfo (optional) - an object containing retry information:retryCountnumber - the number of times this alarm event has been retried.isRetryboolean -trueif this alarm event is a retry,falseotherwise.
- None.
export class MyDurableObject extends DurableObject { async alarm(alarmInfo) { if (alarmInfo?.isRetry) { console.log(`Alarm retry attempt ${alarmInfo.retryCount}`); } await this.processScheduledTask(); }}export class MyDurableObject extends DurableObject<Env> { async alarm(alarmInfo?: AlarmInvocationInfo): Promise<void> { if (alarmInfo?.isRetry) { console.log(`Alarm retry attempt ${alarmInfo.retryCount}`); } await this.processScheduledTask(); }}-
webSocketMessage(ws WebSocket, message string | ArrayBuffer): void | Promise<void>-
Called by the system when an accepted WebSocket receives a message.
-
This method is not called for WebSocket control frames. The system will respond to an incoming WebSocket protocol ping ↗ automatically without interrupting hibernation.
-
This method can be
async.
-
wsWebSocket - the WebSocket ↗ that received the message. Use this reference to send responses or access serialized attachments.messagestring | ArrayBuffer - the message data. Text messages arrive asstring, binary messages asArrayBuffer.
- None.
export class MyDurableObject extends DurableObject { async webSocketMessage(ws, message) { if (typeof message === "string") { ws.send(`Received: ${message}`); } else { ws.send(`Received ${message.byteLength} bytes`); } }}export class MyDurableObject extends DurableObject<Env> { async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer) { if (typeof message === "string") { ws.send(`Received: ${message}`); } else { ws.send(`Received ${message.byteLength} bytes`); } }}-
webSocketClose(ws WebSocket, code number, reason string, wasClean boolean): void | Promise<void>-
Called by the system when a WebSocket connection is closed.
-
You must call
ws.close(code, reason)inside this handler to complete the WebSocket close handshake. Failing to reciprocate the close will result in1006errors on the client, representing an abnormal closure per the WebSocket specification. -
This method can be
async.
-
wsWebSocket - the WebSocket ↗ that was closed.codenumber - the WebSocket close code ↗ sent by the peer (e.g.,1000for normal closure,1001for going away).reasonstring - a string indicating why the connection was closed. May be empty.wasCleanboolean -trueif the connection closed cleanly with a proper closing handshake,falseotherwise.
- None.
export class MyDurableObject extends DurableObject { async webSocketClose(ws, code, reason, wasClean) { // Complete the WebSocket close handshake ws.close(code, reason); console.log(`WebSocket closed: code=${code}, reason=${reason}`); }}export class MyDurableObject extends DurableObject<Env> { async webSocketClose(ws: WebSocket, code: number, reason: string, wasClean: boolean) { // Complete the WebSocket close handshake ws.close(code, reason); console.log(`WebSocket closed: code=${code}, reason=${reason}`); }}-
webSocketError(ws WebSocket, error unknown): void | Promise<void>-
Called by the system when a non-disconnection error occurs on a WebSocket connection.
-
This method can be
async.
-
wsWebSocket - the WebSocket ↗ that encountered an error.errorunknown - the error that occurred. May be anErrorobject or another type depending on the error source.
- None.
export class MyDurableObject extends DurableObject { async webSocketError(ws, error) { const message = error instanceof Error ? error.message : String(error); console.error(`WebSocket error: ${message}`); }}export class MyDurableObject extends DurableObject<Env> { async webSocketError(ws: WebSocket, error: unknown) { const message = error instanceof Error ? error.message : String(error); console.error(`WebSocket error: ${message}`); }}ctx is a readonly property of type DurableObjectState providing access to storage, WebSocket management, and other instance-specific functionality.
env contains the environment bindings available to this Durable Object, as defined in your Wrangler configuration.
- Use WebSockets for WebSocket handler best practices.
- Alarms API for scheduling future work.
- RPC methods for type-safe method calls.
Was this helpful?
- Resources
- API
- New to Cloudflare?
- Directory
- Sponsorships
- Open Source
- Support
- Help Center
- System Status
- Compliance
- GDPR
- Company
- cloudflare.com
- Our team
- Careers
- © 2026 Cloudflare, Inc.
- Privacy Policy
- Terms of Use
- Report Security Issues
- Trademark
-