D1 (SQLite)
Cloudflare D1 is Void's default SQLite database. Start with a schema; Void manages the database locally and when you deploy.
Local Database
The dev server and local void db commands share the same database. If cloudflare.d1_databases in void.config.ts declares the D1 binding, Void uses its ID. A preview_database_id takes precedence during local development.
To store local data outside .void, set voidPlugin({ persistTo: 'local-state' }) in your Vite config. Start the dev server once to record that directory before running database commands. After changing the Vite config, start it again to refresh it. Frameworks that manage their own Cloudflare runtime use .wrangler/state.
Migrations & Prototyping
Use void db push to apply schema changes locally without creating migration files. Before deploying, generate and commit migrations:
void db generate
void db migrate # apply locally
void deploy # apply remotely and deploySee Database commands for the full workflow.
Batch Operations
D1 supports batching multiple statements into a single round-trip:
import { users, posts } from '@schema';
import { db, eq } from 'void/db';
await db.batch([
db.delete(posts).where(eq(posts.userId, userId)),
db.delete(users).where(eq(users.id, userId)),
]);Read replication
If someone in Tokyo opens a profile stored in a D1 database in Europe, read replication lets D1 read from a nearby replica. To enable it, set readReplication in void.config.ts and run void deploy.
import { defineConfig } from 'void/config';
export default defineConfig({
database: { readReplication: true },
});New databases start with replication off. On both Cloudflare and a Void platform, deploying with true enables replicas for an existing database too. Set it to false and deploy to turn them off. Omitting the option keeps the current setting.
Previously deployed databases
Void 0.21.3 started enabling replicas automatically. If you deployed while that was the default, your database may already have them. To turn them off, upgrade Void, set database: { readReplication: false }, and deploy. For a self-hosted platform, upgrade the platform first. If it cannot apply the setting, the CLI stops before uploading your app.
Inside a Void request, queries through db share a session. Later reads in the same session see at least what the first query saw. A new request can reach a replica that hasn’t caught up yet. You can read from the primary when you need the latest data, or carry a bookmark to see a change you just saved.
In a framework handler outside Void’s request scope, each operation on db starts on the primary. Use createDb(binding) to start a session that can read from a replica. For raw D1 queries or another query library, call binding.withSession(). A query on the bare binding reads from the primary.
Avoid stale reads with a primary-first session
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:
import { users } from '@schema';
import { env } from 'cloudflare:workers';
import { defineHandler } from 'void';
import { createDb } from 'void/db';
export const GET = defineHandler(async () => {
const primaryDb = createDb(env.DB, { session: 'first-primary' });
return primaryDb.select().from(users).all();
});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.
See your writes in subsequent requests
Suppose you change your name on /profile. When the form redirects back to your profile, you want to see the name you just saved. A D1 bookmark from the save tells D1 how far a replica must have caught up before it can serve that next read.
For a browser form, a cookie can carry the bookmark across a redirect. This middleware reads the cookie before the handler runs and sets it again after the query finishes.
// 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');
});The middleware covers /profile and its subpaths. Include every route that saves or displays the profile, including redirect destinations. Await the database work in your handler or loader so the bookmark includes it. Local requests made with void/client share the session. If you need a newer bookmark or an independent primary-first read after using db, create a separate client with createDb.
The next request needs to reach D1 to see the new name. Disable ISR on these pages with export const revalidate = 0 and bypass any existing response caches. The private, no-store header prevents browsers and shared caches from storing new responses.
Use a different cookie name for each database and environment. Pass the bookmark back as D1 supplied it. Clearing or expiring the cookie starts a new session without the earlier bookmark.
API requests with concurrent clients
If two requests save changes at the same time, their responses can arrive in the opposite order. With cookies, the last response can overwrite a newer bookmark. For a browser API client, send the bookmark in an X-DB-Bookmark header and keep the newest one. Bookmarks from the same database sort in order.
Here’s the same profile example for /api/profile and its subpaths. Use the combined middleware if your app also needs bookmarks on ordinary navigation and form submissions.
// 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');
});In the browser, keep the bookmark in localStorage so tabs can share it. Use a key unique to the database and the signed-in account. A Web Lock lets one tab at a time compare its response with the stored bookmark. This example requires HTTPS or localhost and a browser with Web Locks and local storage.
// 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;
};
}Now save the new name and read the profile back through the same client.
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 first await saves the bookmark before the second request starts. Use the wrapper with endpoints that return data directly. Browser redirects and form submissions use the cookie in the previous example.
Supporting both transports
If your profile has both a form and an API, read the cookie and header together and pass the newer bookmark to D1. Return the resulting bookmark in both places. This example covers /profile and /api/profile, including their subpaths. Disable ISR on the participating pages.
The fetch wrapper keeps the newest bookmark even when responses arrive out of order. Cookies can still arrive out of order. Use a primary-first session if a redirect must show the latest value.
// 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:
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
Use env.DB from cloudflare:workers with another query library or the raw D1 API:
Kysely
import { env } from 'cloudflare:workers';
import { Kysely } from 'kysely';
import { D1Dialect } from 'kysely-d1';
const db = new Kysely<Database>({ dialect: new D1Dialect({ database: env.DB }) });Raw D1
import { env } from 'cloudflare:workers';
const { results } = await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(userId).all();Void still handles binding inference and deployment regardless of which query layer you use.
⚠️ Meta framework limitation
Nuxt and SvelteKit 2 do not support cloudflare:workers imports during local development. Use void/db or your framework's binding access API. SvelteKit 3 supports these imports.