Skip to content

Commit 38409d0

Browse files
committed
chore: improve D1 replicas and bookmarks docs
1 parent ae3087d commit 38409d0

2 files changed

Lines changed: 180 additions & 11 deletions

File tree

‎docs/guide/database/d1.md‎

Lines changed: 175 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,15 @@ await db.batch([
4343

4444
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.
4545

46-
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:
46+
::: warning
47+
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.
48+
:::
49+
50+
For raw D1 calls or another query library, use `withSession()` to read from replicas. A bare D1 binding reads from the primary.
51+
52+
### Avoid stale reads with a primary-first session {#reading-from-the-primary}
53+
54+
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:
4755

4856
```ts
4957
import { users } from '@schema';
@@ -59,14 +67,24 @@ export const GET = defineHandler(async () => {
5967

6068
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.
6169

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

6672
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.
6773

74+
::: warning
75+
Bookmarks do not affect cached responses. Disable ISR for pages that require fresh reads (`export const revalidate = 0` in the page's `.server.ts` file), and do not serve these requests from shared response caches.
76+
:::
77+
6878
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:
6979

80+
::: warning
81+
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.
82+
:::
83+
84+
::: note
85+
To use cookies and API headers together, see [Supporting both transports](#supporting-both-transports).
86+
:::
87+
7088
```ts
7189
// middleware/01.database.ts
7290
import { getCookie, setCookie } from 'hono/cookie';
@@ -90,16 +108,31 @@ export default defineMiddleware(async (c, next) => {
90108
});
91109
```
92110

93-
Your handlers and loaders keep importing `db` from `void/db`. No cookie is created automatically. This example uses a session cookie; if you add an expiry, the freshness guarantee from that bookmark ends when it expires. Parallel responses can overwrite the cookie out of order, so this simple transport does not guarantee monotonic bookmarks across concurrent requests.
111+
#### API requests with concurrent clients
112+
113+
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.
114+
115+
For requests made through the browser fetch wrapper below, exchange bookmarks using this middleware:
116+
117+
::: warning
118+
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.
119+
:::
94120

95-
For API clients, exchange a header instead:
121+
::: note
122+
To use cookies and API headers together, see [Supporting both transports](#supporting-both-transports).
123+
:::
96124

97125
```ts
98126
// middleware/01.database.ts
99127
import { defineMiddleware } from 'void';
100128
import { getBookmark, setSession } from 'void/db';
101129

102130
export default defineMiddleware(async (c, next) => {
131+
if (!c.req.path.startsWith('/api/')) {
132+
await next();
133+
return;
134+
}
135+
103136
setSession(c.req.header('X-DB-Bookmark') ?? 'first-unconstrained');
104137
await next();
105138
const bookmark = getBookmark();
@@ -110,9 +143,143 @@ export default defineMiddleware(async (c, next) => {
110143
});
111144
```
112145

113-
The client must save the returned header and send it on its next request. For a separate D1 binding or a framework handler outside Void's request scope, pass the bookmark to `createDb(binding, { session: bookmark })` and read the resulting bookmark with `getBookmark(client)`.
146+
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.
147+
148+
```ts
149+
// src/bookmark-fetch.ts
150+
export function createBookmarkFetch(scope: string) {
151+
const key = `d1-bookmark:${scope}`;
152+
153+
return async function bookmarkFetch(path: string, init: RequestInit = {}): Promise<Response> {
154+
const url = new URL(path, location.origin);
155+
if (url.origin !== location.origin || !url.pathname.startsWith('/api/')) {
156+
throw new Error('bookmarkFetch requires a same-origin /api/ URL.');
157+
}
158+
159+
const bookmark = localStorage.getItem(key);
160+
const headers = new Headers(init.headers);
161+
headers.delete('X-DB-Bookmark');
162+
if (bookmark) headers.set('X-DB-Bookmark', bookmark);
163+
164+
const response = await fetch(url, {
165+
...init,
166+
headers,
167+
credentials: 'same-origin',
168+
cache: 'no-store',
169+
redirect: 'error',
170+
});
171+
172+
const returned = response.headers.get('X-DB-Bookmark');
173+
if (returned) {
174+
await navigator.locks.request(key, () => {
175+
const current = localStorage.getItem(key);
176+
if (current === null || returned > current) {
177+
localStorage.setItem(key, returned);
178+
}
179+
});
180+
}
181+
182+
return response;
183+
};
184+
}
185+
```
186+
187+
Use the wrapper for each participating API request. For example, with an existing profile API:
188+
189+
```ts
190+
import { createBookmarkFetch } from './bookmark-fetch';
191+
192+
export async function saveAndReadProfile(accountId: string, name: string) {
193+
const api = createBookmarkFetch(`app-db:${accountId}`);
194+
const saved = await api('/api/profile', {
195+
method: 'POST',
196+
headers: { 'Content-Type': 'text/plain' },
197+
body: name,
198+
});
199+
if (!saved.ok) throw new Error(`Save failed: ${saved.status}`);
200+
201+
// Sends at least the completed save's bookmark.
202+
const response = await api('/api/profile');
203+
if (!response.ok) throw new Error(`Read failed: ${response.status}`);
204+
return response.json();
205+
}
206+
```
207+
208+
The wrapper saves the newest bookmark before resolving, so subsequent requests inherit its progress even if concurrent responses arrive out of order.
209+
210+
Use API endpoints that return data, not redirects.
211+
212+
#### Supporting both transports
213+
214+
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.
215+
216+
::: warning
217+
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.
218+
:::
219+
220+
```ts
221+
// middleware/01.database.ts
222+
import { getCookie, setCookie } from 'hono/cookie';
223+
import { defineMiddleware } from 'void';
224+
import { getBookmark, setSession } from 'void/db';
225+
226+
export default defineMiddleware(async (c, next) => {
227+
const incoming: string[] = [];
228+
229+
// Cookie input: navigation, forms, and same-origin fetch requests.
230+
// Remove for header-only use.
231+
const cookieBookmark = getCookie(c, 'db-bookmark');
232+
if (cookieBookmark) incoming.push(cookieBookmark);
233+
234+
// Header input: the fetch wrapper's saved progress.
235+
// Remove for cookie-only use.
236+
const headerBookmark = c.req.header('X-DB-Bookmark');
237+
if (headerBookmark) incoming.push(headerBookmark);
238+
239+
// Bookmarks from the same database sort oldest to newest.
240+
setSession(incoming.sort().at(-1) ?? 'first-unconstrained');
241+
await next();
242+
243+
const bookmark = getBookmark();
244+
if (bookmark) {
245+
// Cookie output: progress for subsequent navigation and forms.
246+
// Remove for header-only use.
247+
setCookie(c, 'db-bookmark', bookmark, {
248+
httpOnly: true,
249+
secure: new URL(c.req.url).protocol === 'https:',
250+
sameSite: 'Lax',
251+
path: '/',
252+
});
253+
254+
// Header output: progress for the fetch wrapper.
255+
// Remove for cookie-only use.
256+
c.header('X-DB-Bookmark', bookmark);
257+
}
258+
259+
c.header('Cache-Control', 'private, no-store');
260+
});
261+
```
262+
263+
#### Using `createDb`
114264

115-
Bookmarks constrain database queries, not cached responses. Disable ISR for pages that require this guarantee (`export const revalidate = 0` in the page's `.server.ts` file), and do not serve those requests from shared response caches. A bookmark also does not guarantee visibility of a later write from another client, such as an independent payment webhook; use a primary-first session when you need the latest primary data.
265+
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:
266+
267+
```ts
268+
import { users } from '@schema';
269+
import { createDb, getBookmark } from 'void/db';
270+
271+
export async function readUsers(request: Request, binding: D1Database) {
272+
const client = createDb(binding, {
273+
session: request.headers.get('X-DB-Bookmark') ?? 'first-unconstrained',
274+
});
275+
const result = await client.select().from(users).all();
276+
277+
const headers = new Headers({ 'Cache-Control': 'private, no-store' });
278+
const bookmark = getBookmark(client);
279+
if (bookmark) headers.set('X-DB-Bookmark', bookmark);
280+
return Response.json(result, { headers });
281+
}
282+
```
116283

117284
## Alternative Query Layers
118285

‎docs/reference/api/database.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,9 +37,9 @@ import { createDb } from 'void/db';
3737
const db = createDb(env.MY_OTHER_DB);
3838
```
3939

40-
For a fresh D1 read, pass `{ session: 'first-primary' }` and create the client inside the request. The default, `'first-unconstrained'`, allows the first query to use a replica. Both keep your schema and query types. See [Read replication](../../guide/database/d1.md#read-replication).
40+
For a fresh D1 read, pass `{ session: 'first-primary' }` and create the client inside the request. The default, `'first-unconstrained'`, allows the first query to use a replica. Both keep your schema and query types. See [Avoid stale reads with a primary-first session](../../guide/database/d1.md#reading-from-the-primary).
4141

42-
The `session` option also accepts a D1 bookmark from a previous request. Use `getBookmark(client)` after queries to obtain the bookmark to return to your client.
42+
The `session` option also accepts a D1 bookmark from a previous request. Use `getBookmark(client)` after queries to obtain the bookmark to return to your client. See [Using `createDb`](../../guide/database/d1.md#using-createdb) for an example.
4343

4444
For PostgreSQL and MySQL projects, pass a connection string.
4545

@@ -81,7 +81,9 @@ D1 only. Return the default request session's bookmark, or pass a client returne
8181
function getBookmark(client?: DrizzleD1Database<Schema>): D1SessionBookmark | null;
8282
```
8383

84-
`setSession()` and the no-argument `getBookmark()` require Void's request scope. For framework handlers outside that scope, use `createDb(binding, { session: bookmark })` and `getBookmark(client)` instead. See [carrying bookmarks between requests](../../guide/database/d1.md#cross-request-bookmarks) for middleware examples.
84+
`setSession()` and the no-argument `getBookmark()` require Void's request scope. For a framework-owned endpoint, such as an Astro API route, use an [explicit client](../../guide/database/d1.md#using-createdb) instead.
85+
86+
For cookie and header middleware, a browser fetch wrapper, and guidance on combining both transports, see [See your writes in subsequent requests](../../guide/database/d1.md#cross-request-bookmarks).
8587

8688
## Query Operators {#query-operators}
8789

0 commit comments

Comments
 (0)