Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
51ad087
fix: add repro tests for #783
kossnocorp Nov 11, 2026
d47ece4
chore: set up playground for D1 bookmarks
kossnocorp Nov 13, 2026
8483f9e
feat: prototype support for D1 bookmarks
kossnocorp Nov 13, 2026
437ba61
chore: clean up D1 bookmark code
kossnocorp Nov 16, 2026
4bac342
chore: fix stale path after #841
kossnocorp Nov 16, 2026
832a00c
chore: improve D1 replicas and bookmarks docs
kossnocorp Nov 16, 2026
3e0295c
chore: fix formatting in D1 bookmarks playground
kossnocorp Nov 16, 2026
b5cb03a
chore: fix failing test after runtime reorg
kossnocorp Nov 16, 2026
08bc42d
chore: clean up Sessions API playground
kossnocorp Nov 16, 2026
ca29b7f
chore: add server fetch test breaking `setSession`
kossnocorp Nov 17, 2026
86c24c5
chore: fix server fetch calling `setSession`, add missing test cases
kossnocorp Nov 17, 2026
4e3344c
chore: update pnpm-lock.yaml
kossnocorp Nov 17, 2026
0a8809f
chore: prevent accidental db initialization when awaiting or inspecting
kossnocorp Nov 17, 2026
39a1a07
chore: throw clear errors when calling `setSession` and `getBookmark`…
kossnocorp Nov 17, 2026
4fb8f6f
chore: fix D1 playground types
kossnocorp Nov 17, 2026
64cc977
chore: make bookmark option explicit to prevent typos in `first-*` li…
kossnocorp Nov 17, 2026
9582e1f
chore: make generated `getBookmark` less restrictive
kossnocorp Nov 17, 2026
056e632
chore: clarify D1 sessions & bookmarks docs
kossnocorp Nov 17, 2026
4318605
chore: kill D1 bookmarks playground
kossnocorp Nov 17, 2026
2f9ba18
feat: add `database.readReplication` option, make D1 replication opt-in
kossnocorp Nov 17, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
286 changes: 283 additions & 3 deletions docs/guide/database/d1.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,47 @@ await db.batch([

## Read replication

Void enables [D1 read replication](https://developers.cloudflare.com/d1/best-practices/read-replication/) when it provisions a database. To enable it on an existing database, run `void deploy --platform cloudflare --provision`. Queries through `db` from `void/db` use a D1 session for each Void request, so reads can run near the request and later queries in that request see at least the same data. Framework handlers without Void's request scope start each database operation on the primary. `createDb` starts a replica-capable session for the binding you pass it.
::: warning Previously deployed databases
Void **0.21.3** introduced automatic D1 read replication. If you deployed with that version or a later version before replication became opt-in, your database may already have replicas enabled. Replicas can serve stale data between requests.

Replicas can lag between requests. Authentication checks use the primary so a lagging replica can't accept a revoked session. For other reads that need the latest primary data, create a client inside the request:
Unless your app intentionally uses replicas with the consistency handling described below, we recommend upgrading to a Void version that supports `database.readReplication`, setting it to `false` in `void.config.ts`, and running `void deploy`:

```ts
import { defineConfig } from 'void/config';

export default defineConfig({
database: { readReplication: false },
});
```

If you self-host the Void platform, upgrade it as well before deploying. Upgrading alone or omitting the option does **not** disable existing replication.
:::

[D1 read replication](https://developers.cloudflare.com/d1/best-practices/read-replication/) is opt-in. Enable it in `void.config.ts`, then run `void deploy`:

```ts
import { defineConfig } from 'void/config';

export default defineConfig({
database: { readReplication: true },
});
```

This enables replication for new and existing application D1 databases on both direct Cloudflare and Void platform deployments. Set `readReplication: false` and deploy again to disable replication.

When you omit `readReplication`, deployment leaves the database's replication setting unchanged. New databases default to replication off. Removing the option from a database that already has replication enabled keeps it enabled.

Queries through `db` from `void/db` use a D1 session for each Void request. With replication enabled, reads can run near the request and later queries in that request see at least the same data. Framework handlers without Void's request scope start each database operation on the primary. `createDb` starts a replica-capable session for the binding you pass it.

::: warning
Replicas can lag between requests. [Carry a bookmark](#cross-request-bookmarks) to preserve previously observed database state, or use a [primary-first session](#reading-from-the-primary) when you need the latest primary data.
:::

For raw D1 calls or another query library, use `withSession()` to read from replicas. A bare D1 binding reads from the primary.

### Avoid stale reads with a primary-first session {#reading-from-the-primary}

Authentication checks use the primary so a lagging replica can't accept a revoked session. For other reads that need the latest primary data, create a client inside the request:

```ts
import { users } from '@schema';
Expand All @@ -59,7 +97,249 @@ export const GET = defineHandler(async () => {

With `session: 'first-primary'`, the first query reads from the primary and later queries see at least the same data. The default, `'first-unconstrained'`, allows the first query to use a replica.

For raw D1 calls or another query library, use `withSession()` to read from replicas. A bare D1 binding reads from the primary.
### See your writes in subsequent requests {#cross-request-bookmarks}

To make a read after a save see that save in a later request, carry a [D1 bookmark](https://developers.cloudflare.com/d1/best-practices/read-replication/#start-a-session-from-previous-context-bookmark) between requests. A bookmark allows D1 to use a replica that has caught up to at least the previously observed database state.

Keep saved bookmarks scoped to the database that issued them. Use separate cookie names or browser-storage keys for different databases and environments, and clear saved bookmarks when switching to a different database. Clearing a bookmark starts a new consistency chain; subsequent requests no longer carry the previous bookmark's guarantee. Treat bookmarks as opaque strings rather than parsing or constructing them.

::: warning
Bookmarks constrain database queries, not cached responses. A cached response can predate your save without running a query. Disable ISR for participating pages (`export const revalidate = 0` in the page's `.server.ts` file) and bypass any existing response caches for these routes. Setting response headers alone does not bypass an ISR cache hit.
:::

Use middleware to set the default `db` session before your handlers or Pages loaders run, and return its bookmark after their queries. For a browser app, a cookie carries it through redirects and navigation:
Comment thread
Brooooooklyn marked this conversation as resolved.
Resolved

This example opts `/profile` and its subpaths into bookmark handling and `Cache-Control: private, no-store`, preventing browser and shared response-cache storage. Change the path to cover your participating reads, saves, and redirect destinations. Routes outside this scope keep their existing cache policies.

Local server-side requests through `void/client` share that session. If middleware runs again, repeating an already satisfied session requirement preserves the session and its database progress. For an independent primary-first read or a newer bookmark after using `db`, use `createDb` instead.

Await consistency-critical database work before returning from your handler or loader. Deferred or background queries that finish after middleware captures the response bookmark are not guaranteed to be reflected in it.

::: warning
Concurrent responses can overwrite this cookie with an older bookmark. The [header-based recipe](#api-requests-with-concurrent-clients) retains the newest bookmark across concurrent API responses. Clearing or expiring bookmark storage starts a new bookmark chain.
:::

::: note
To use cookies and API headers together, see [Supporting both transports](#supporting-both-transports).
:::

```ts
// middleware/01.database.ts
import { getCookie, setCookie } from 'hono/cookie';
import { defineMiddleware } from 'void';
import { getBookmark, setSession } from 'void/db';

export default defineMiddleware(async (c, next) => {
const path = c.req.path;
if (path !== '/profile' && !path.startsWith('/profile/')) {
await next();
return;
}

const incoming = getCookie(c, 'db-bookmark');
setSession(incoming === undefined ? 'first-unconstrained' : { bookmark: incoming });
await next();

const bookmark = getBookmark();
if (bookmark) {
setCookie(c, 'db-bookmark', bookmark, {
httpOnly: true,
secure: new URL(c.req.url).protocol === 'https:',
sameSite: 'Lax',
path: '/',
});
}
c.header('Cache-Control', 'private, no-store');
Comment thread
kossnocorp marked this conversation as resolved.
Resolved
});
```

#### API requests with concurrent clients

For browser API requests, exchange an `X-DB-Bookmark` header and retain the newest bookmark. [D1 bookmarks are lexicographically sortable](https://developers.cloudflare.com/d1/reference/time-travel/#bookmarks), so an older response must not replace a newer bookmark from the same database.

For requests made through the browser fetch wrapper below, exchange bookmarks using this middleware. It opts only `/api/profile` and its subpaths into bookmark handling and uncached responses; adjust the path to match your participating API routes:

::: warning
This recipe carries bookmarks only through the fetch wrapper below, not ordinary navigation, form submissions, or Pages requests. It does not share bookmarks with the cookie-based recipe.
:::

::: note
To use cookies and API headers together, see [Supporting both transports](#supporting-both-transports).
:::

```ts
// middleware/01.database.ts
import { defineMiddleware } from 'void';
import { getBookmark, setSession } from 'void/db';

export default defineMiddleware(async (c, next) => {
const path = c.req.path;
if (path !== '/api/profile' && !path.startsWith('/api/profile/')) {
await next();
return;
}

const incoming = c.req.header('X-DB-Bookmark');
setSession(incoming === undefined ? 'first-unconstrained' : { bookmark: incoming });
await next();
const bookmark = getBookmark();
if (bookmark) {
c.header('X-DB-Bookmark', bookmark);
}
c.header('Cache-Control', 'private, no-store');
});
```

On the browser, send the saved bookmark and atomically retain the newest returned value using [Web Locks](https://developer.mozilla.org/en-US/docs/Web/API/Web_Locks_API). This requires HTTPS (or localhost), browser storage, and Web Locks support. Use a scope unique to the database and signed-in account; same-origin tabs with the same scope share progress.

```ts
// src/bookmark-fetch.ts
export function createBookmarkFetch(scope: string) {
const key = `d1-bookmark:${scope}`;

return async function bookmarkFetch(path: string, init: RequestInit = {}): Promise<Response> {
const url = new URL(path, location.origin);
if (url.origin !== location.origin || !url.pathname.startsWith('/api/')) {
throw new Error('bookmarkFetch requires a same-origin /api/ URL.');
}

const bookmark = localStorage.getItem(key);
const headers = new Headers(init.headers);
headers.delete('X-DB-Bookmark');
if (bookmark) headers.set('X-DB-Bookmark', bookmark);

const response = await fetch(url, {
...init,
headers,
credentials: 'same-origin',
cache: 'no-store',
redirect: 'error',
});

const returned = response.headers.get('X-DB-Bookmark');
if (returned) {
await navigator.locks.request(key, () => {
const current = localStorage.getItem(key);
if (current === null || returned > current) {
localStorage.setItem(key, returned);
}
});
}

return response;
};
}
```

Use the wrapper for each participating API request. For example, with an existing profile API:

```ts
import { createBookmarkFetch } from './bookmark-fetch';

export async function saveAndReadProfile(accountId: string, name: string) {
const api = createBookmarkFetch(`app-db:${accountId}`);
const saved = await api('/api/profile', {
method: 'POST',
headers: { 'Content-Type': 'text/plain' },
body: name,
});
if (!saved.ok) throw new Error(`Save failed: ${saved.status}`);

// Sends at least the completed save's bookmark.
const response = await api('/api/profile');
if (!response.ok) throw new Error(`Read failed: ${response.status}`);
return response.json();
}
```

The wrapper saves the newest bookmark before resolving, so subsequent requests inherit its progress even if concurrent responses arrive out of order.

Use API endpoints that return data, not redirects.

#### Supporting both transports

Use this single middleware with the fetch wrapper above to support API requests alongside browser navigation and forms. It selects the newest incoming bookmark for the same database and returns it through both transports.

Only `/profile`, `/api/profile`, and their subpaths participate and receive `Cache-Control: private, no-store`. Adjust this list for your app, disable ISR on participating pages, and leave unrelated routes' cache policies unchanged.

::: warning
The fetch wrapper retains the newest bookmark across concurrent responses, but cookies can still be overwritten out of order. For a guaranteed fresh read on a redirect's destination page, use a primary-first session.
:::

```ts
// middleware/01.database.ts
import { getCookie, setCookie } from 'hono/cookie';
import { defineMiddleware } from 'void';
import { getBookmark, setSession } from 'void/db';

export default defineMiddleware(async (c, next) => {
const path = c.req.path;
const participates = ['/profile', '/api/profile'].some(
(base) => path === base || path.startsWith(`${base}/`),
);
if (!participates) {
await next();
return;
}

const incoming: string[] = [];

// Cookie input: navigation, forms, and same-origin fetch requests.
// Remove for header-only use.
const cookieBookmark = getCookie(c, 'db-bookmark');
if (cookieBookmark) incoming.push(cookieBookmark);

// Header input: the fetch wrapper's saved progress.
// Remove for cookie-only use.
const headerBookmark = c.req.header('X-DB-Bookmark');
if (headerBookmark) incoming.push(headerBookmark);

// Bookmarks from the same database sort oldest to newest.
const newest = incoming.sort().at(-1);
setSession(newest === undefined ? 'first-unconstrained' : { bookmark: newest });
await next();

const bookmark = getBookmark();
if (bookmark) {
// Cookie output: progress for subsequent navigation and forms.
// Remove for header-only use.
setCookie(c, 'db-bookmark', bookmark, {
httpOnly: true,
secure: new URL(c.req.url).protocol === 'https:',
sameSite: 'Lax',
path: '/',
});

// Header output: progress for the fetch wrapper.
// Remove for cookie-only use.
c.header('X-DB-Bookmark', bookmark);
}

c.header('Cache-Control', 'private, no-store');
});
```

#### Using `createDb`

For another D1 binding or a framework-owned endpoint, such as an Astro API route, create a client with the incoming bookmark. After querying, return `getBookmark(client)` in the response header:

```ts
import { users } from '@schema';
import { createDb, getBookmark } from 'void/db';

export async function readUsers(request: Request, binding: D1Database) {
const incoming = request.headers.get('X-DB-Bookmark');
const client = createDb(binding, {
session: incoming === null ? 'first-unconstrained' : { bookmark: incoming },
});
const result = await client.select().from(users).all();

const headers = new Headers({ 'Cache-Control': 'private, no-store' });
const bookmark = getBookmark(client);
if (bookmark) headers.set('X-DB-Bookmark', bookmark);
return Response.json(result, { headers });
}
```

## Alternative Query Layers

Expand Down
2 changes: 1 addition & 1 deletion docs/reference/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ Import Void's app-facing APIs from these paths:
| `void/schema-pg` | Re-exports [`drizzle-orm/pg-core`](https://orm.drizzle.team/docs/column-types/pg) for PostgreSQL table and column builders |
| `void/schema-mysql` | Re-exports `drizzle-orm/mysql-core` for MySQL table and column builders |
| `void/database-provider` | `defineDatabaseProvider` and adapter types for `void db connect --provider` |
| `void/db` | `db` (Drizzle D1, PostgreSQL, or MySQL instance for the active dialect), `createDb`, query operators (`eq`, `and`, `or`, `desc`, `like`, `inArray`, etc.) |
| `void/db` | `db` (Drizzle D1, PostgreSQL, or MySQL instance for the active dialect), `createDb`, D1 session helpers (`setSession`, `getBookmark`), query operators (`eq`, `and`, `or`, `desc`, `like`, `inArray`, etc.) |
| `void/seed` | `defineSeed`, `SeedContext`, `SeedFn` for programmatic `void db seed` modules |
| `void/kv` | `kv`, `createKV`, typed KV client/map types |
| `void/storage` | `storage`, `createStorage` for the inferred R2 binding or a specific `R2Bucket` |
Expand Down
Loading
Loading