---
title: "Moving a Hono API from Postgres or D1 to SurrealDB Earth"
description: "Replace D1 or Postgres in a Hono Worker with SurrealDB Earth: database per tenant, per-request clients, secrets, CRUD routes and SurrealQL."
url: https://surrealdb.com/blog/moving-a-hono-api-from-postgres-or-d1-to-surrealdb-earth
date: 2026-11-20
authors: "Tobie Morgan Hitchcock"
---

# Moving a Hono API from Postgres or D1 to SurrealDB Earth

![Moving a Hono API from Postgres or D1 to SurrealDB Earth](https://cdn.surrealdb.com/jincti9qc35x5yr8l9znom0f.auto)

[Hono](https://hono.dev) is a small, fast web framework built on Web Standard APIs. The same Hono app runs on Cloudflare Workers, Deno, Bun and Node.js, which makes it a common choice for APIs that run at the edge. [SurrealDB Earth](https://surrealdb.com/docs/manage/instances/earth) is serverless SurrealDB on the Cloudflare network: an instance scales to zero when it is idle, adds compute as load grows, and keeps its data in the region you choose.

This guide moves a Hono API on Cloudflare Workers from Postgres or D1 to SurrealDB Earth. The Worker opens a client of the SurrealDB JavaScript SDK for each request, gives each tenant a database of its own inside one Earth instance, and stores its data as SurrealDB records. It covers SurrealDB 4 on Earth, the JavaScript SDK (`surrealdb` on npm) 2.2.2, and Hono 4.13.16.

## What you need

- A Hono app on Cloudflare Workers, with Wrangler 4.
- An Earth instance. Create one from the Deploy page in [SurrealDB Studio](https://studio.surrealdb.com), or with `surreal cloud instance deploy`.

## How is an Earth database addressed?

An Earth instance holds data on three levels: the instance, a namespace inside it, and a database inside the namespace. Namespaces and databases are the same scopes as on any SurrealDB server.

| Level | How a request selects it | If it selects nothing |
| --- | --- | --- |
| Instance | The address `https://<instance-id>.surrealdb.earth` | The request goes nowhere |
| Namespace | The `namespace` option of `connect()`, which the SDK sends as the `surreal-ns` header over HTTP | `main` |
| Database | The `database` option of `connect()` or `use()`, which the SDK sends as the `surreal-db` header over HTTP | `main` |

The dashboard of an Earth instance in Studio shows its public endpoint, in the form `wss://<instance-id>.surrealdb.earth/rpc`. For HTTP, use the same host with `https://`. The SDK adds `/rpc` to a remote URL that does not already end with it, so `https://<instance-id>.surrealdb.earth` is all the Worker needs.

Earth defines a namespace or a database on the first request that uses it, so a new tenant's database needs no separate create step. On a self-hosted SurrealDB server, the same database is created with [`DEFINE DATABASE`](https://surrealdb.com/docs/reference/query-language/statements/define/database), and a namespace with [`DEFINE NAMESPACE`](https://surrealdb.com/docs/reference/query-language/statements/define/namespace).

## Should each tenant get a database or an instance?

The choice follows from which settings your tenants share. Data residency, capabilities, network policy and the cell limit belong to an instance, and every database inside the instance shares them.

- **A database per tenant** suits tenants that need the same settings. The Worker keeps one URL and one set of credentials, and the tenant selects the database on each request. This is the setup this guide builds.
- **An instance per tenant** suits tenants that need different settings, such as one tenant whose data must stay in the European Union while another's may be stored anywhere, or tenants whose usage you bill separately, since Earth measures usage per instance.

A transaction covers one instance, so data that one transaction must write together belongs in one instance. [Namespaces and databases for multi-tenancy](https://surrealdb.com/docs/learn/schema-management/multi-tenancy/namespace-and-database-architecture) compares the options in more detail.

## How does the Worker sign in to Earth?

The Worker signs in as a user defined on the namespace, which can reach every tenant database in that namespace and nothing outside it. Define the user in Studio's query view on the instance with [`DEFINE USER`](https://surrealdb.com/docs/reference/query-language/statements/define/user):

```surql
DEFINE USER app ON NAMESPACE PASSWORD 'hunter123' ROLES EDITOR;
```

The `EDITOR` role lets the user define databases, tables and fields, and read and write records, but not manage other users. Store the password and an admin token for the provisioning route as Worker secrets:

```bash
npx wrangler secret put SURREAL_PASS
npx wrangler secret put ADMIN_TOKEN
```

Keep the rest of the connection settings in plain variables, because they are not secret:

```toml
name = "notes-api"
main = "src/index.ts"
compatibility_date = "2026-11-01"

[vars]
SURREAL_URL = "https://<instance-id>.surrealdb.earth"
SURREAL_NAMESPACE = "main"
SURREAL_USER = "app"
```

The SDK takes the credentials in the `authentication` option of `connect()`. With a username and password, it signs in when it connects. The option also accepts a token, or a function that returns either, so a Worker can reuse a token it obtained earlier instead of signing in on every request.

## How do you open a connection per request?

A D1 binding or a Postgres pool lives as long as the Worker isolate and is shared by its requests. A Worker cannot share a SurrealDB connection between requests in the same way, so create a client inside each request, tie it to the request's abort signal, and close it when the request ends.

Over HTTP this has little overhead. An HTTP client keeps no connection open between queries: each query is an HTTP request of its own, so there is no socket to set up per request and no pool to manage. Connecting signs in, and the client then sends the queries that the route makes.

```ts
import { type Context, Hono } from "hono";
import { bearerAuth } from "hono/bearer-auth";
import { RecordId, Surreal, SurrealRequestScope, Table, surql } from "surrealdb";

type Env = {
	SURREAL_URL: string;
	SURREAL_NAMESPACE: string;
	SURREAL_USER: string;
	SURREAL_PASS: string;
	ADMIN_TOKEN: string;
};

// A tenant name becomes a database name, so it may only use these characters.
const TENANT = /^[a-z0-9_]{1,32}$/;

const app = new Hono<{ Bindings: Env; Variables: { db: SurrealRequestScope } }>();

async function connect(env: Env, database?: string) {
	const db = new Surreal();
	await db.connect(env.SURREAL_URL, {
		namespace: env.SURREAL_NAMESPACE,
		database,
		authentication: {
			namespace: env.SURREAL_NAMESPACE,
			username: env.SURREAL_USER,
			password: env.SURREAL_PASS,
		},
		requestTimeout: 5_000,
	});
	return db;
}

app.use("/t/:tenant/*", async (c, next) => {
	const tenant = c.req.param("tenant");
	if (!TENANT.test(tenant)) return c.json({ error: "invalid tenant name" }, 400);

	const db = await connect(c.env, tenant);
	c.set("db", db.withSignal(c.req.raw.signal));
	try {
		await next();
	} finally {
		await db.close();
	}
});
```

`TENANT` is a regular expression that checks the tenant name before it is used as a database name. The middleware rejects any name that is not between 1 and 32 lowercase letters, digits and underscores, which also keeps the name safe to place in the `DEFINE DATABASE` statement of the provisioning route below. In a production app, take the tenant from the signed-in user's verified claims, such as a field of a JWT that your auth layer has checked, rather than from the path alone.

`withSignal()` returns a view of the client whose queries are abandoned when the request is aborted, for example when the caller disconnects.

## How do you define the schema?

D1 and Postgres apps usually keep their schema in migration files. In SurrealDB, the schema is a set of [`DEFINE TABLE`](https://surrealdb.com/docs/reference/query-language/statements/define/table), [`DEFINE FIELD`](https://surrealdb.com/docs/reference/query-language/statements/define/field) and [`DEFINE INDEX`](https://surrealdb.com/docs/reference/query-language/statements/define/indexes) statements. Written with `IF NOT EXISTS`, each statement defines its table, field or index only if it does not exist yet, so the same schema can run any number of times. A provisioning route runs it once for each new tenant:

```ts
const SCHEMA = `
BEGIN;
DEFINE TABLE IF NOT EXISTS note SCHEMAFULL;
DEFINE FIELD IF NOT EXISTS title ON note TYPE string ASSERT string::len($value) > 0;
DEFINE FIELD IF NOT EXISTS body ON note TYPE string DEFAULT "";
DEFINE FIELD IF NOT EXISTS done ON note TYPE bool DEFAULT false;
DEFINE FIELD IF NOT EXISTS created_at ON note TYPE datetime DEFAULT time::now() READONLY;
DEFINE INDEX IF NOT EXISTS note_done ON note FIELDS done;
DEFINE TABLE IF NOT EXISTS archive SCHEMALESS;
COMMIT;
`;

app.use(
	"/admin/*",
	bearerAuth({ verifyToken: (token, c: Context<{ Bindings: Env }>) => token === c.env.ADMIN_TOKEN }),
);

app.post("/admin/tenants/:tenant", async (c) => {
	const tenant = c.req.param("tenant");
	if (!TENANT.test(tenant)) return c.json({ error: "invalid tenant name" }, 400);

	const db = await connect(c.env);
	try {
		await db.query(`DEFINE DATABASE IF NOT EXISTS ${tenant}`);
		await db.use({ namespace: c.env.SURREAL_NAMESPACE, database: tenant });
		await db.query(SCHEMA);
		return c.json({ ok: true }, 201);
	} finally {
		await db.close();
	}
});
```

The route is for your own operators, so Hono's [bearer auth middleware](https://hono.dev/docs/middleware/builtin/bearer-auth) admits only requests that carry the `ADMIN_TOKEN` secret.

Earth defines the tenant's database on its first use, so there the `DEFINE DATABASE IF NOT EXISTS` statement finds the database already defined or defines it, with the same result. The statement lets the same route run against a self-hosted SurrealDB server, which needs a database to be defined before use. `use()` then switches the open session to the tenant's database.

`BEGIN` and `COMMIT` send the whole schema as one transaction, so it applies completely or not at all. On Earth this is also faster, because each transaction waits once for durable storage, rather than once for every statement.

## What does the CRUD route set look like?

Each route calls the SDK once, in the order create, read, update and delete. The `note` helper returns the key of a record ID rather than the whole ID, so clients see `"yy0pzsdr6fw8icdqyer1"` rather than `note:yy0pzsdr6fw8icdqyer1`.

```ts
// Return the key of a record id, so that clients see "yy0pzsdr6fw8icdqyer1" rather than note:yy0pzsdr6fw8icdqyer1
const note = (r: any) => ({ ...r, id: String(r.id.id) });

// Create a note
app.post("/t/:tenant/notes", async (c) => {
	const { title, body } = await c.req.json();
	const [row] = await c.var.db.create(new Table("note")).content({ title, body });
	return c.json(note(row), 201);
});

// Read every note, or with ?done=true or ?done=false only those, oldest first
app.get("/t/:tenant/notes", async (c) => {
	const done = c.req.query("done");
	const [rows] = await c.var.db.query<[any[]]>(
		done === undefined
			? surql`SELECT * FROM note ORDER BY created_at`
			: surql`SELECT * FROM note WHERE done = ${done === "true"} ORDER BY created_at`,
	);
	return c.json(rows.map(note));
});

// Read one note
app.get("/t/:tenant/notes/:id", async (c) => {
	const row = await c.var.db.select(new RecordId("note", c.req.param("id")));
	return row ? c.json(note(row)) : c.json({ error: "not found" }, 404);
});

// Update a note
app.patch("/t/:tenant/notes/:id", async (c) => {
	const row = await c.var.db.update(new RecordId("note", c.req.param("id"))).merge(await c.req.json());
	return row ? c.json(note(row)) : c.json({ error: "not found" }, 404);
});

// Delete a note
app.delete("/t/:tenant/notes/:id", async (c) => {
	await c.var.db.delete(new RecordId("note", c.req.param("id")));
	return c.body(null, 204);
});

export default app;
```

A few details in these routes:

- **IDs.** Creating a record in a table without giving it an ID generates a random 20-character key, which is SurrealDB's default. The key is unique within the table, so the API can use it in its URLs as it is.
- **Parameters.** The `surql` tag turns each `${}` value into a bound parameter, so the `done` filter is sent separately from the query text rather than joined into it.
- **Order.** SurrealDB returns the records of a `SELECT` in no particular order unless the query has an `ORDER BY` clause, so the list route sorts by `created_at`.
- **Validation.** A note with an empty title fails the `ASSERT` on the `title` field, and the record is not written.

## How do records differ from rows?

A SurrealDB [record](https://surrealdb.com/docs/reference/query-language/language-primitives/data-types/record-ids) is a document stored in a table and addressed by a record ID of the form `table:key`. The table name is part of the ID, so a `RecordId` value always says which table it points to. A table in SurrealDB plays the part of a table in Postgres or D1, and a record plays the part of a row.

| D1 or Postgres | SurrealDB |
| --- | --- |
| `CREATE TABLE` in migration files | `DEFINE TABLE` and `DEFINE FIELD`, with `IF NOT EXISTS` |
| An `id SERIAL` or `uuid` column | A record ID such as `note:yy0pzsdr6fw8icdqyer1`, random by default |
| A foreign key column | A field of type `record<note>` that holds the linked record's ID |
| `$1` or `?` placeholders | `${value}` inside the `surql` tag, sent as a bound parameter |
| `SELECT ... WHERE id = $1` | `db.select(new RecordId("note", id))` |
| A pool or binding per Worker isolate | A client per request |
| The `env.DB` binding | A URL variable, a namespace and user name, and a password secret |

Much of the SQL you know carries over. `SELECT * FROM note WHERE done = true` is valid SurrealQL, and a `SCHEMAFULL` table rejects fields that its schema does not define, as a SQL table rejects unknown columns.

## How do transactions work?

Every statement in SurrealDB runs in a transaction. A statement on its own commits on its own, so a `CREATE` that fails leaves nothing behind. When several statements must succeed or fail together, group them in one manual transaction with [`BEGIN` and `COMMIT`](https://surrealdb.com/docs/learn/querying/concepts-and-guides/transactions#manual-transactions), and a failure in any of them undoes them all.

The SDK's `transaction()` method does this for you. It wraps a list of statements in `BEGIN` and `COMMIT` and sends them as one HTTP request, so the transaction starts and ends within that request:

```ts
// Move a note to the archive: both statements commit, or neither does
app.post("/t/:tenant/notes/:id/archive", async (c) => {
	const id = new RecordId("note", c.req.param("id"));
	const [archived] = await c.var.db.transaction<[any, unknown]>(
		[
			surql`CREATE ONLY archive SET original = ${id}, title = (SELECT VALUE title FROM ONLY ${id})`,
			surql`DELETE ${id}`,
		],
		{ retry: true },
	);
	return c.json({ archived: String(archived.id.id) });
});
```

This takes the place of a D1 `batch()` call or a Postgres `BEGIN` ... `COMMIT` block. With `retry: true`, the SDK runs the whole transaction again if it fails because another transaction wrote the same records at the same time.

A transaction that reads a result and then decides what to send next needs a WebSocket connection that stays open for the transaction, which a Worker can hold only within one request. [Connecting from serverless and edge](https://surrealdb.com/docs/learn/querying/concepts-and-guides/connecting-from-serverless-and-edge#transactions-over-http) covers both kinds.

## Migration checklist

- Define a namespace user for the Worker with `DEFINE USER ... ON NAMESPACE ... ROLES EDITOR`.
- Set `SURREAL_URL`, `SURREAL_NAMESPACE` and `SURREAL_USER` as Worker variables, and `SURREAL_PASS` and `ADMIN_TOKEN` as secrets.
- Take the tenant from a verified claim and pass it as the `database` option.
- Create the client in each request, tie it to the request with `withSignal()`, and close it in `finally`.
- Replace migration files with `DEFINE ... IF NOT EXISTS` statements, run once per tenant in one transaction.
- Replace foreign key columns with record links, and `$1` placeholders with the `surql` tag.
- Add `ORDER BY` to every query whose order matters.
- Replace `batch()` calls and `BEGIN` blocks with `db.transaction()`.

## Summary

A Hono Worker moves to SurrealDB Earth with a few changes: one SDK client per request, a database per tenant inside one instance, a namespace user instead of a database binding, and `DEFINE` statements instead of migration files. Earth defines each tenant's database on first use and scales to zero when nobody is using it.

To start, create an instance with [SurrealDB Earth](https://surrealdb.com/earth), and see the [JavaScript SDK documentation](https://surrealdb.com/docs/reference/javascript) and [Hono](https://hono.dev) for the rest of the APIs.
