Skip to content

Durable Object Base Class

Last updated View as MarkdownAgent setup

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!")

Methods

fetch

  • 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.

Parameters

  • request Request - the incoming HTTP request object.

Return values

  • A Response or Promise<Response>.

Example

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!");