Skip to content

Tutorial with SQL API

This guide will instruct you through:

  • Writing a JavaScript class that defines a Durable Object.
  • Using Durable Objects SQL API to query a Durable Object's private, embedded SQLite database.
  • Instantiating and communicating with a Durable Object from another Worker.
  • Deploying a Durable Object and a Worker that communicates with a Durable Object.

Prerequisites

  1. Sign up for a Cloudflare account.
  2. Install Node.js.

Node.js version manager

Use a Node version manager like Volta or nvm to avoid permission issues and change Node.js versions. Wrangler, discussed later in this guide, requires a Node version of 16.17.0 or later.

1. Enable Durable Objects in the dashboard

To enable Durable Objects, you will need to purchase the Workers Paid plan:

  1. Log in to the Cloudflare dashboard, and select your account.
  2. Go to Workers & Pages > Plans.
  3. Select Purchase Workers Paid and complete the payment process to enable Durable Objects.

2. Create a Worker project to access Durable Objects

You will access your Durable Object from a Worker. Your Worker application is an interface to interact with your Durable Object.

To create a Worker project, run:

Terminal window
npm create cloudflare@latest -- durable-object-starter

Running create cloudflare@latest will install Wrangler, the Workers CLI. You will use Wrangler to test and deploy your project.

For setup, select the following options:

  • For What would you like to start with?, choose Hello World example.
  • For Which template would you like to use?, choose Hello World Worker Using Durable Objects.
  • For Which language do you want to use?, choose TypeScript.
  • For Do you want to use git for version control?, choose Yes.
  • For Do you want to deploy your application?, choose No (we will be making some changes before deploying).

This will create a new directory, which will include either a src/index.js or src/index.ts file to write your code and a wrangler.toml configuration file.

Move into your new directory:

Terminal window
cd durable-object-starter

3. Write a class to define a Durable Object that uses SQL API

Before you create and access a Durable Object, its behavior must be defined by an ordinary exported JavaScript class.

Your MyDurableObject class will have a constructor with two parameters. The first parameter, ctx, passed to the class constructor contains state specific to the Durable Object, including methods for accessing storage. The second parameter, env, contains any bindings you have associated with the Worker when you uploaded it.

export class MyDurableObject extends DurableObject {
constructor(ctx, env) {}
}

Workers communicate with a Durable Object using remote-procedure call. Public methods on a Durable Object class are exposed as RPC methods to be called by another Worker.

Your file should now look like:

export class MyDurableObject extends DurableObject {
constructor(ctx, env) {}
async sayHello() {
let result = this.ctx.storage.sql
.exec("SELECT 'Hello, World!' as greeting")
.one();
return result.greeting;
}
}

In the code above, you have:

  1. Defined a RPC method, sayHello(), that can be called by a Worker to communicate with a Durable Object.
  2. Accessed a Durable Object's attached storage, which is a private SQLite database only accesible to the object, using SQL API methods (sql.exec()) available on ctx.storage .
  3. Returned an object representing the single row query result using one(), which checks that the query result has exactly one row.
  4. Return the greeting column from the row object result.

4. Instantiate and communicate with a Durable Object

A Worker is used to access Durable Objects.

To communicate with a Durable Object, the Worker's fetch handler should look like the following:

export default {
async fetch(request, env) {
let id = env.MY_DURABLE_OBJECT.idFromName(new URL(request.url).pathname);
let stub = env.MY_DURABLE_OBJECT.get(id);
let greeting = await stub.sayHello();
return new Response(greeting);
},
};

In the code above, you have:

  1. Exported your Worker's main event handlers, such as the fetch() handler for receiving HTTP requests.
  2. Passed env into the fetch() handler. Bindings are delivered as a property of the environment object passed as the second parameter when an event handler or class constructor is invoked. By calling the idFromName() function on the binding, you use a string-derived object ID. You can also ask the system to generate random unique IDs. System-generated unique IDs have better performance characteristics, but require you to store the ID somewhere to access the Object again later.
  3. Derived an object ID from the URL path. MY_DURABLE_OBJECT.idFromName() always returns the same ID when given the same string as input (and called on the same class), but never the same ID for two different strings (or for different classes). In this case, you are creating a new object for each unique path.
  4. Constructed the stub for the Durable Object using the ID. A stub is a client object used to send messages to the Durable Object.
  5. Called a Durable Object by invoking a RPC method, sayHello(), on the Durable Object, which returns a Hello, World! string greeting.
  6. Received an HTTP response back to the client by constructing a HTTP Response with return new Response().

Refer to Access a Durable Object from a Worker to learn more about communicating with a Durable Object.

5. Configure Durable Object bindings

Bindings allow your Workers to interact with resources on the Cloudflare developer platform. The Durable Object bindings in your Worker project's wrangler.toml will include a binding name (for this guide, use MY_DURABLE_OBJECT) and the class name (MyDurableObject).

[[durable_objects.bindings]]
name = "MY_DURABLE_OBJECT"
class_name = "MyDurableObject"
# or
[durable_objects]
bindings = [
{ name = "MY_DURABLE_OBJECT", class_name = "MyDurableObject" }
]

The [[durable_objects.bindings]] section contains the following fields:

  • name - Required. The binding name to use within your Worker.
  • class_name - Required. The class name you wish to bind to.
  • script_name - Optional. Defaults to the current environment's Worker code.

6. Configure Durable Object class with SQLite storage backend

A migration is a mapping process from a class name to a runtime state. You perform a migration when creating a new Durable Object class, or when renaming, deleting or transferring an existing Durable Object class.

Migrations are performed through the [[migrations]] configurations key in your wrangler.toml file.

The Durable Object migration to create a new Durable Object class with SQLite storage backend will look like the following in your Worker's wrangler.toml file:

[[migrations]]
tag = "v1" # Should be unique for each entry
new_sqlite_classes = ["MyDurableObject"] # Array of new classes

Refer to Durable Objects migrations to learn more about the migration process.

7. Develop a Durable Object Worker locally

To test your Durable Object locally, run wrangler dev:

Terminal window
npx wrangler dev

In your console, you should see aHello world string returned by the Durable Object.

8. Deploy your Durable Object Worker

To deploy your Durable Object Worker:

Terminal window
npx wrangler deploy

Once deployed, you should be able to see your newly created Durable Object Worker on the Cloudflare dashboard, Workers & Pages > Overview.

Preview your Durable Object Worker at <YOUR_WORKER>.<YOUR_SUBDOMAIN>.workers.dev.

By finishing this tutorial, you have successfully created, tested and deployed a Durable Object.