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
- Sign up for a Cloudflare account ↗.
- 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:
- Log in to the Cloudflare dashboard ↗, and select your account.
- Go to Workers & Pages > Plans.
- 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:
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:
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.
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:
In the code above, you have:
- Defined a RPC method,
sayHello()
, that can be called by a Worker to communicate with a Durable Object. - 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 onctx.storage
. - Returned an object representing the single row query result using
one()
, which checks that the query result has exactly one row. - 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:
In the code above, you have:
- Exported your Worker’s main event handlers, such as the
fetch()
handler for receiving HTTP requests. - Passed
env
into thefetch()
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 theidFromName()
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. - 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. - Constructed the stub for the Durable Object using the ID. A stub is a client object used to send messages to the Durable Object.
- Called a Durable Object by invoking a RPC method,
sayHello()
, on the Durable Object, which returns aHello, World!
string greeting. - 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
).
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:
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
:
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:
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.
Related resources
- Create Durable Object stubs
- Access Durable Objects Storage
- Miniflare ↗ - Helpful tools for mocking and testing your Durable Objects.