Skip to content

D1 is a SQL database that a Worker reaches through a binding. On one machine, workerd keeps each database in one Durable Object, under .wrangler/state/workerd/d1/. In a cluster, workerd copies it to the bucket, as it does any Durable Object, so another instance can serve it. Read the Cloudflare D1 documentation for the API.

Example

The D1 example implements a guestbook with a D1 database.

index.jsjs
const SCHEMA = [
  `CREATE TABLE IF NOT EXISTS entries (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    message TEXT NOT NULL,
    at INTEGER NOT NULL
  )`,
  "CREATE INDEX IF NOT EXISTS entries_at ON entries (at DESC)",
];

export default {
  async fetch(request, env) {
    await env.DB.batch(SCHEMA.map((sql) => env.DB.prepare(sql)));
    const url = new URL(request.url);

    if (request.method === "POST") {
      const { name, message } = await request.json();
      const written = await env.DB
        .prepare("INSERT INTO entries (name, message, at) VALUES (?, ?, ?)")
        .bind(name, message, Date.now())
        .run();
      return Response.json({
        id: written.meta.last_row_id,
        changes: written.meta.changes,
      }, { status: 201 });
    }

    const count = await env.DB
      .prepare("SELECT count(*) AS n FROM entries")
      .first("n");
    if (url.pathname === "/count") return Response.json({ count });

    const { results } = await env.DB
      .prepare(
        "SELECT id, name, message, at FROM entries ORDER BY at DESC LIMIT ?",
      )
      .bind(20)
      .all();
    return Response.json({ count, entries: results });
  },
};
wrangler.jsoncjsonc
{
  "name": "d1",
  "main": "index.js",
  "compatibility_date": "2026-01-01",
  "no_bundle": true,
  "d1_databases": [
    {
      "binding": "DB",
      "database_name": "guestbook",
      "database_id": "00000000-0000-0000-0000-000000000000"
    }
  ]
}

D1 is experimental, so it needs --experimental:

npx workerd serve --experimental ./d1/wrangler.jsonc
curl -X POST --data '{"name": "Ada", "message": "Hello"}' http://localhost:8787/
curl http://localhost:8787/

Differences from Cloudflare

  • A d1_databases entry names its database by preview_database_id, else database_id, else the binding name, as wrangler dev does. workerd creates a database on first use, so a typo in the name opens an empty database.
  • workerd ignores migrations_dir and applies no migrations. Create the schema from the Worker, as the example does.
  • SQLite’s limits apply, not D1’s.
  • A database has the write throughput of one Durable Object. Use more databases to increase it.
  • workerd has no read replicas. Every query runs on the primary.
  • workerd has no D1 REST API and no Time Travel.

See also Cloudflare compatibility.

Type to search…

↑↓ navigate↵ selectEsc close