You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit 38409d0
Browse filesBrowse the repository at this point in the historyBrowse files
Copy file name to clipboardExpand all lines: docs/guide/database/d1.md
+175-8Lines changed: 175 additions & 8 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -43,7 +43,15 @@ await db.batch([
43
43
44
44
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.
45
45
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:
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.
61
69
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}
65
71
66
72
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.
67
73
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
+
68
78
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:
69
79
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).
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
+
:::
94
120
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).
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.
const api =createBookmarkFetch(`app-db:${accountId}`);
194
+
const saved =awaitapi('/api/profile', {
195
+
method: 'POST',
196
+
headers: { 'Content-Type': 'text/plain' },
197
+
body: name,
198
+
});
199
+
if (!saved.ok) thrownewError(`Save failed: ${saved.status}`);
200
+
201
+
// Sends at least the completed save's bookmark.
202
+
const response =awaitapi('/api/profile');
203
+
if (!response.ok) thrownewError(`Read failed: ${response.status}`);
204
+
returnresponse.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.
// 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: newURL(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`
114
264
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:
Copy file name to clipboardExpand all lines: docs/reference/api/database.md
+5-3Lines changed: 5 additions & 3 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -37,9 +37,9 @@ import { createDb } from 'void/db';
37
37
const db =createDb(env.MY_OTHER_DB);
38
38
```
39
39
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).
41
41
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.
43
43
44
44
For PostgreSQL and MySQL projects, pass a connection string.
45
45
@@ -81,7 +81,9 @@ D1 only. Return the default request session's bookmark, or pass a client returne
81
81
function getBookmark(client?:DrizzleD1Database<Schema>):D1SessionBookmark|null;
82
82
```
83
83
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).
0 commit comments