Mastering Void: Full-Stack Apps on Cloudflare Workers

Mastering Void: Full-Stack Apps on Cloudflare Workers

Summary

Void is Cloudflare's full-stack framework for Workers, built on Vite. One project holds your routes, your pages, a typed D1 database, KV, R2, queues, crons, auth, server-sent events and WebSockets, and one command deploys the lot. It went 1.0 in October 2026 and it's moving fast.

This guide starts with the basics: what Void is, a running app in ten minutes, routing, rendering HTML without a frontend framework, the database, storage, auth, background work, realtime, AI and email, testing, and deploying. Then it builds a real full-stack app with Datastar, a team board where everyone viewing a board sees changes live, and finishes with Void inside an Astro project and an honest comparison with plain Workers.

Every example in it was run against a pinned Void release before it went in. Void ships often, so this is a living document, and I keep it current.

What Void Is, and When to Reach for It

Void is Cloudflare's full-stack framework for Workers, built on Vite. You write files in a few known folders, and Void turns them into a Worker with routes, pages, a database, storage, background jobs and a deploy command.

This chapter covers what that means in practice, plus two traps I'd want flagged before typing npm install.

I ran everything in this guide against Void 1.12.2 on Node 24.22.3. Void is young: 1.0 hit npm on October 15, 2026, and by November 27 there were 21 published 1.x versions. Pin your version, read the release notes, and treat this guide as a living document.

What you get

Void sits inside your Vite config as a plugin. From there it reads a handful of folders:

  • routes/ for HTTP endpoints, one file per URL, one export per method
  • pages/ for server-rendered pages with React, Vue, Svelte or Solid
  • middleware/ for code that runs on every request
  • db/ for a Drizzle schema and generated SQL migrations
  • crons/, queues/ and workflows/ for background work

Then there are imports: void/db for a typed database (D1 by default), void/kv, void/storage for R2, plus auth, AI, email, SSE, WebSockets and Durable Objects.

The part that feels different is resource inference. Import db from void/db and Void works out that the app needs a database: a local one in dev, a real one on deploy. When I wired Void into an Astro app for an earlier post, I never declared a D1 binding. Void saw db/schema.ts and wrote this itself:

{
  "d1_databases": [
    { "binding": "DB", "database_name": "default", "database_id": "local" }
  ]
}

What it replaces from plain Wrangler

With plain Wrangler, you write wrangler.jsonc by hand. You create the D1 database, paste its ID, add each KV namespace and bucket, pick compatibility flags, and run migrations yourself.

Void generates that file. Building the scratch app for these chapters wrote a dist/ssr/wrangler.json with the nodejs_als flag, an ASSETS binding for public/, and required secrets taken from my env.ts:

// dist/ssr/wrangler.json (excerpt)
{
  "compatibility_flags": ["nodejs_als"],
  "compatibility_date": "2026-02-24",
  "assets": { "binding": "ASSETS", "directory": "../client" },
  "secrets": {
    "required": ["BASIC_AUTH_USERNAME", "BASIC_AUTH_PASSWORD"]
  }
}

Per the docs, void deploy then handles the account side: missing resources, migrations, the upload, and resource IDs recorded in void.lock.json. Chapter 12 runs it for real.

Four kinds of app

Void detects what you're building. You can also lock it in void.config.ts with inference.appType, which takes one of four values:

  • void: a native Void app. Void owns routing. It can be API-only (just routes/), a single-page app plus an API, or full-stack with pages/.
  • framework: an existing Vite framework like Astro, SvelteKit, Nuxt or TanStack Start. The framework keeps its routing and rendering; Void adds resources, migrations and deploys.
  • spa: a client-side app. Unknown paths serve index.html.
  • static: a folder of prebuilt HTML from something like VitePress.

This guide builds a native app. The docs limit Void-managed auth and Durable State to native apps (framework apps use Better Auth directly), and Part 2 needs both. Framework mode gets its own chapter near the end, condensed from my Astro tests.

Check your Node version first

Void 1.x needs Node ^24.22.0 || >=26.12.0. That's stricter than it looks, and the failure is quiet.

I have Node 24.12.0 installed through nvm, so I tried it:

node --version
# v24.12.0
npm install -D void
npm ls void
# └── void@0.10.13

No error. npm picked the newest version whose engines field matched my Node: a pre-1.0 release with a different project layout. The current docs fail on top of it with errors that send you hunting through config files.

Check before you install:

node --version   # needs 24.22+ or 26.12+

The npm name has a past

The void name on npm dates back to 2014. Versions 1.0.0 through 1.0.2 were published in 2015 and 2017, long before this framework, and they're gone now:

npm view void@1.0.0 version
# npm error 404 No match found for version 1.0.0

npm never lets a version number be reused, so Cloudflare's first 1.x release is 1.0.3. That makes void@1.0.x a risky pin, and with this release pace you want a current version anyway. Pin it exactly:

npm install -D -E void@1.12.2

Without -E, npm writes ^1.12.2. At this pace, I want upgrades to be a decision.

Where it deploys

Void has two deploy targets. The first is your own Cloudflare account, through void deploy --platform cloudflare. The docs say native apps run on Workers Free within its quotas; a few features, like sandboxes, need Workers Paid.

The second is a Void platform: a self-hosted deploy service you install into a company Cloudflare account, so a team can ship without sharing Cloudflare credentials. It needs Workers for Platforms (paid), a hosted PostgreSQL database and a login provider. There's no hosted Void service to sign up for.

This guide uses your own account. The platform gets a section in chapter 12.

When I'd reach for it

I'd start a new Void app for an internal tool, a small SaaS backend or a team board: a handful of routes, a database, maybe a cron job. That's where generated bindings and one deploy command save the most typing.

I'd think twice about moving an app that already runs fine on Wrangler. void deploy can link an existing Worker, but you'd be trading a setup you understand for a young framework's conventions.

React is optional, too. The init wizard pushes you toward a UI framework, but a native app can be nothing more than routes/ returning HTML. That's what this guide builds toward: server-rendered Hono JSX, with Datastar for interactivity in Part 2.

Next, we install it and get a real app answering requests on localhost in chapter 2.

Ten Minutes to a Running App

This chapter gets a Void app running on your machine and building for production. I ran every command here in an empty folder on Node 24.22.3. These are the versions it pulled:

Package

Version

void

1.12.2

vite-plus

1.8.0

vite (Vite+ core)

8.3.8001

hono

4.13.19

typescript

7.0.2

The deploy is the one step I describe from the docs instead of running. It needs a Cloudflare login, and I cover the deploy itself in chapter 12.

Install and run setup

Start in an empty directory and check Node first (chapter 1 explains why):

node --version   # 24.22+ or 26.12+
mkdir my-app && cd my-app
npm install -D -E void@1.12.2
npx void init

void init is a wizard. Its first line in my run was Empty project detected. Creating a Pages starter. Then it asks about Git, a toolchain (Vite+ or plain Vite), a UI framework, a starter (static, SQLite, PostgreSQL or MySQL) and a deploy target.

I picked Vite+, React, the static starter and no deploy target. You can pass the same answers as flags, which is what I'd put in a script:

npx void init --toolchain vite-plus --framework react --starter static --deploy none --no-git

We'll take React back out in chapter 4. The wizard has no "no framework" option, so a starter is the quickest way to get every config file written for you.

One trap I hit. My first attempt ran npm init -y before installing Void. npm 11 writes "type": "commonjs" into that package.json, void init kept it, and npm run dev died:

Error: Failed to resolve "@void/react/plugin". This package is ESM only
but it was tried to load by `require`.

The CLI reference says Void writes vite.config.mts in a CommonJS package. In 1.12.2 it wrote vite.config.ts. Skip npm init and let npm install create package.json. Then void init sets "type": "module" itself.

What setup wrote

After init, my folder looked like this:

my-app/
  .gitignore
  .void/
  .void-wrangler.jsonc
  AGENTS.md
  package.json
  pages/
    index.tsx
    style.css
  public/
  tsconfig.json
  vite.config.ts
  void.config.ts

The scripts in package.json go through Vite+ (vp), with a postinstall that generates Void's types:

{
  "scripts": {
    "dev": "vp dev",
    "build": "vp build",
    "preview": "vp preview",
    "postinstall": "void prepare"
  }
}

vite.config.ts registers voidPlugin() and the React adapter, plus Cloudflare's oxlint preset for vp lint. Every Void app needs voidPlugin() in its Vite config; the rest is optional.

AGENTS.md is short. It tells coding agents that the project uses Void and to read the Markdown docs shipped in node_modules/void/docs/, which match your installed version. The docs say init also links Void's agent skills when it detects a supported agent. My run was non-interactive in a bare folder and only wrote AGENTS.md.

.gitignore already excludes .void, .wrangler, .cloudflare, .void-wrangler.jsonc, dist and every .env file.

Start the dev server

There's no void dev. I tried:

npx void dev
# ■ cli: Unknown command 'dev'. Run `void --help` for usage.

Dev runs through Vite:

npm run dev

It came up on port 5173 in about 1.3 seconds. The page is the React starter, and the headers give away who's serving it:

curl -I http://localhost:5173/
# HTTP/1.1 200 OK
# content-type: text/html; charset=utf-8
# x-powered-by: Void

That request ran inside Cloudflare's local runtime. Void uses the Cloudflare Vite plugin, which runs your Worker in workerd during development.

Now add an API route. Create routes/api/hello.ts:

import { defineHandler } from 'void';

export const GET = defineHandler(() => {
  return { message: 'Hello from Void' };
});
curl http://localhost:5173/api/hello
# {"message":"Hello from Void"}

I didn't restart anything. New route files showed up on the next request.

void.config.ts and void.lock.json

void.config.ts is your settings file. Init wrote this one:

// Generated by void init.
import { defineConfig } from 'void/config';

export default defineConfig({
  "routing": {
    "typedRoutes": true
  },
  "worker": {
    "compatibility_date": "2026-02-24"
  }
});

routing holds typed routes, headers, redirects and rewrites (chapter 4). worker holds Worker settings like the compatibility date and CPU limits. inference lets you override what Void detects.

void.lock.json is the other file you commit. It records the IDs of resources Void provisions and the history of migrations it has applied. My scratch app never connected to Cloudflare, so it never got one. The docs are firm about it once it exists: commit it after the first deploy, and don't reorder its migration entries.

.void-wrangler.jsonc is generated config for Cloudflare tooling. Leave it ignored.

Build it

npm run build

The build wrote two folders. dist/client/ holds the files from public/. dist/ssr/ holds the Worker bundle and a generated wrangler.json. Each route file became its own small chunk. npm run preview serves that production build on port 4173, which is where I checked that dev-only routes really disappear (chapter 3 covers those).

Deploying, from the docs

I didn't deploy this app. Per the docs, the first deploy to your own account is two commands:

npx void cloudflare login
npx void deploy --platform cloudflare

void cloudflare login opens a browser and stores the session in your system keychain. No separate Wrangler login is needed. void deploy will also start that login on its own when it needs one, so the first command is optional.

According to the docs, deploy then creates any missing resources, builds the app, checks secrets and migrations, uploads the Worker, verifies it's ready and switches traffic. It prints the URL and saves the target, so later deploys are just npx void deploy. CI uses a CLOUDFLARE_API_TOKEN secret instead of a browser login.

I cover the deploy itself in chapter 12, with a real account, the lock file it produces and what rollback does and doesn't undo.

Next up in chapter 3: the routes/ folder, and everything a route file can return.

Routing

Every server endpoint in a Void app is a file in routes/. The path of the file is the URL. The exports are the HTTP methods. Under the hood it's Hono, so if you've written a Hono app you already know the request context.

I built every route in this chapter in a scratch app on Void 1.12.2 and hit each one with curl. The outputs below are what came back.

Files become URLs

Here's the tree I tested:

routes/
  hello.ts                →  /hello
  api/status.ts           →  /api/status
  api/users/[id].ts       →  /api/users/42
  files/[...path].ts      →  /files/docs/2026/report.pdf
  (admin)/dashboard.ts    →  /dashboard
  api/debug.dev.ts        →  /api/debug, dev only
  _helpers.ts             →  not a route

Each file exports a constant per method, wrapped in defineHandler:

// routes/api/status.ts
import { defineHandler } from 'void';

export const GET = defineHandler(() => {
  return { ok: true, time: new Date().toISOString() };
});

GET handlers answer HEAD too. I didn't write one, and curl -I /api/status still got a 200 with the JSON content type.

What a handler returns

This is the part that makes Void handlers short. You can return plain values and Void picks the response:

  • a string becomes text/html; charset=utf-8
  • an object, array, number or boolean becomes JSON
  • null or undefined becomes 204 No Content
  • a Response goes out untouched

A string:

// routes/hello.ts
import { defineHandler } from 'void';

export const GET = defineHandler(() => {
  return '<h1>Hello from Void</h1>';
});
curl -i http://localhost:5173/hello
# HTTP/1.1 200 OK
# content-type: text/html; charset=utf-8
#
# <h1>Hello from Void</h1>

An object came back as application/json, as you'd expect. A handler with no return (a POST that only does work) answered 204 No Content.

When you need a status code or your own headers, build the Response yourself:

// routes/api/teapot.ts
import { defineHandler } from 'void';

export const GET = defineHandler(() => {
  return new Response('I am a teapot', {
    status: 418,
    headers: { 'content-type': 'text/plain' },
  });
});
curl -i http://localhost:5173/api/teapot
# HTTP/1.1 418 I'm a teapot
# content-type: text/plain

The handler also gets Hono's context as c, so Hono's helpers work too. defineHandler((c) => c.json({ created: true }, 201)) answered 201 Created when I tried it. I reach for those when the status matters and return plain values everywhere else.

Params and catch-alls

Square brackets make a parameter. Read it with Hono's c.req.param():

// routes/api/users/[id].ts
import { defineHandler } from 'void';

export const GET = defineHandler((c) => {
  const id = c.req.param('id');
  return { id, name: `User ${id}` };
});
curl http://localhost:5173/api/users/42
# {"id":"42","name":"User 42"}

Params are always strings, and in 1.12.2 c.req.param() is typed string | undefined. When I passed one straight into a prop typed string, tsc failed with Type 'string | undefined' is not assignable to type 'string'. The params validator below fixes that and checks the value at the same time.

Three dots make a catch-all. The param holds the rest of the path, slashes included:

// routes/files/[...path].ts
import { defineHandler } from 'void';

export const GET = defineHandler((c) => {
  return { path: c.req.param('path'), url: c.req.path };
});
curl http://localhost:5173/files/docs/2026/report.pdf
# {"path":"docs/2026/report.pdf","url":"/files/docs/2026/report.pdf"}

A bare /files returned 404. The catch-all wants at least one segment.

When routes overlap, the docs say the most specific wins: static segments beat params, and catch-alls run last.

Groups, ignored files and environment routes

A folder in parentheses organizes files without touching the URL. routes/(admin)/dashboard.ts answered at /dashboard.

A name that starts with _ keeps a file out of routing, so routes/_helpers.ts is a safe place for shared code. /_helpers returned 404.

A .dev or .prod suffix limits a route to one environment. I wrote routes/api/debug.dev.ts to dump request headers. In npm run dev it returned JSON. In npm run preview, which serves the production build, the same URL returned 404, and the build output had no chunk for it. The docs add that a resource used only by .dev routes won't be provisioned in production.

Validation

defineHandler.withValidator() checks body, query and params with any Standard Schema library. I used Valibot 1.5.0:

npm install valibot
// routes/api/search.ts
import * as v from 'valibot';
import { defineHandler } from 'void';

export const POST = defineHandler.withValidator({
  body: v.object({
    query: v.pipe(v.string(), v.minLength(1)),
    limit: v.optional(v.pipe(v.number(), v.maxValue(100)), 10),
  }),
})(async (c, { body }) => {
  return { query: body.query, limit: body.limit, results: [] };
});

The second argument holds the parsed, typed values. A good request picks up the default:

curl -X POST http://localhost:5173/api/search \
  -H 'content-type: application/json' -d '{"query":"void"}'
# {"query":"void","limit":10,"results":[]}

A bad one never reaches your code. Void answers 400 with every issue:

curl -X POST http://localhost:5173/api/search \
  -H 'content-type: application/json' -d '{"query":"","limit":500}'
# {"error":"Validation failed","issues":[{"slot":"body","issues":[
#   {"message":"Invalid length: Expected >=1 but received 0","path":"query"},
#   {"message":"Invalid value: Expected <=100 but received 500","path":"limit"}]}]}

A form-encoded body (-d 'query=void', no JSON header) also passed. That matters in Part 2, where browser forms post straight to these routes.

Params work the same way, and they fix the typing problem from earlier:

// routes/api/posts/[slug].ts
import * as v from 'valibot';
import { defineHandler } from 'void';

export const GET = defineHandler.withValidator({
  params: v.object({ slug: v.pipe(v.string(), v.regex(/^[a-z0-9-]+$/)) }),
})((c, { params }) => {
  return { slug: params.slug }; // typed as string
});

/api/posts/hello-void returned {"slug":"hello-void"}. /api/posts/Bad_Slug got a 400 with "slot":"params".

Middleware

Global middleware lives in middleware/, and numeric prefixes set the order. This one times every request:

// middleware/01.timing.ts
import { defineMiddleware } from 'void';

export default defineMiddleware(async (c, next) => {
  const start = performance.now();
  await next();
  c.header('Server-Timing', `app;dur=${Math.round(performance.now() - start)}`);
});

Every response, HTML and JSON alike, came back with a header like server-timing: app;dur=5.

For one route, pass middleware to defineHandler before the handler. The docs allow up to five. Returning early short-circuits:

// routes/api/secret.ts
import { defineHandler, defineMiddleware } from 'void';

const requireKey = defineMiddleware(async (c, next) => {
  if (c.req.header('x-api-key') !== 'let-me-in') {
    return c.json({ error: 'missing or wrong key' }, 401);
  }
  await next();
});

export const GET = defineHandler(requireKey, () => {
  return { secret: 'the cake is in the fridge' };
});

Without the header I got a 401. With it, the JSON.

For a quick password on a preview, Void ships basicAuth(). Declare the two values in env.ts, put them in a root .env, and read them through callbacks:

// env.ts
import { defineEnv, string } from 'void/env';

export default defineEnv({
  BASIC_AUTH_USERNAME: string(),
  BASIC_AUTH_PASSWORD: string(),
});
// middleware/02.basic-auth.ts
import { basicAuth } from 'void';
import { env } from 'void/env';

export default basicAuth({
  username: () => env.BASIC_AUTH_USERNAME,
  password: () => env.BASIC_AUTH_PASSWORD,
  realm: 'Preview',
});

Without credentials, every URL returned 401 with www-authenticate: Basic realm="Preview". That included files from public/. With -u admin:<password> it let me through. The dev server restarted itself when .env appeared, so I didn't have to.

Two things to know before relying on it. The two names in env.ts became required production secrets in the build's wrangler.json. And everyone shares that one password. Real user accounts come in chapter 7.

In chapter 4, these routes start returning real pages: HTML without React, using Hono's JSX.

Rendering Without a Framework

Part 2 of this guide builds a full app with Datastar. The server sends HTML, Datastar patches it into the page, and the browser never downloads React. So before we touch a database, the routes need to produce real pages.

This chapter does that in the scratch app from chapters 2 and 3, still on Void 1.12.2. We start with strings, move to Hono's JSX, and finish with the static files and edge rules that sit around your routes.

Strings work, but they don't escape

Chapter 3 showed that a returned string becomes text/html. That's fine for fixed markup. It gets dangerous the moment you interpolate user input:

// routes/unsafe.ts
import { defineHandler } from 'void';

export const GET = defineHandler((c) => {
  const name = c.req.query('name') ?? 'stranger';
  return `<h1>Hello, ${name}</h1>`;
});
curl "http://localhost:5173/unsafe?name=%3Cscript%3Ealert(1)%3C/script%3E"
# <h1>Hello, <script>alert(1)</script></h1>

That script tag went out exactly as sent. A template literal has no idea it's building HTML.

Hono's html tag does. Swap the backticks for it and return through c.html():

// routes/plain.ts
import { html } from 'hono/html';
import { defineHandler } from 'void';

export const GET = defineHandler((c) => {
  const name = c.req.query('name') ?? 'stranger';
  return c.html(html`<!doctype html>
    <h1>Hello, ${name}</h1>`);
});
curl "http://localhost:5173/plain?name=%3Cscript%3Ealert(1)%3C/script%3E"
# <!doctype html>
#     <h1>Hello, &lt;script&gt;alert(1)&lt;/script&gt;</h1>

Same request, escaped output. Void depends on Hono already, and the starter put hono in your dependencies, so the import works without installing anything.

For a few lines, html is enough. For pages with layouts and repeated pieces, I'd rather write JSX.

Switch the app to Hono JSX

Route files use the app's JSX settings. The starter configured React, so React comes out first. Delete pages/ (and public/react.svg if you like), then remove the packages:

rm -rf pages
npm uninstall @void/react react react-dom @types/react @types/react-dom oxc-transform-react

In vite.config.ts, drop voidReact() and point the JSX transform at Hono. I kept the lint block init wrote and changed two lines:

// vite.config.ts
import cloudflare from "@cloudflare/oxlint-config/vite-plus";
import { defineConfig } from "vite-plus";
import { voidPlugin } from "void";

export default defineConfig({
  lint: {
    extends: [cloudflare],
    env: cloudflare.env,
    ignorePatterns: [
      ...cloudflare.ignorePatterns,
      "**/dist/**",
      "**/.void/**",
      "**/.wrangler/**",
      "**/.cloudflare/**",
    ],
  },
  oxc: { jsx: { runtime: "automatic", importSource: "hono/jsx" } },
  plugins: [voidPlugin()],
});

The docs stop there. That's enough for the app to run, but not for TypeScript. Without one more line, tsc failed on every JSX file with This JSX tag requires the module path 'react/jsx-runtime' to exist. Add jsxImportSource to tsconfig.json and drop pages from its include:

{
  "compilerOptions": {
    "jsx": "react-jsx",
    "jsxImportSource": "hono/jsx"
  }
}

I restarted npm run dev after editing the Vite config.

c.html(), and the bare JSX trap

A JSX route is a .tsx file that hands its markup to c.html():

// routes/slow.tsx
import { defineHandler } from 'void';

async function Greeting() {
  await new Promise((resolve) => setTimeout(resolve, 50));
  return <p>Loaded after a wait.</p>;
}

export const GET = defineHandler((c) =>
  c.html(
    <main>
      <h1>Async component</h1>
      <Greeting />
    </main>,
  ),
);

That also shows that Hono JSX components can be async. c.html() waited for Greeting and sent one finished document. Handy when a component needs to query the database.

Now the trap. I expected returning JSX straight from a handler to behave like returning a string. Here's what came back:

// routes/bare.tsx
import { defineHandler } from 'void';

export const GET = defineHandler(() => <h1>No c.html here</h1>);
curl -i http://localhost:5173/bare
# content-type: application/json
#
# {"tag":"h1","props":{"children":"No c.html here"},"children":["No c.html here"],"isEscaped":true}

A JSX element is an object, so Void's return rules serialize it as JSON. Always wrap it in c.html().

Layouts are functions

Routes have no layout convention. A layout is a component that takes children:

// src/components/Layout.tsx
import { raw } from 'hono/html';
import type { Child } from 'hono/jsx';

export function Layout({ title, children }: { title: string; children: Child }) {
  return (
    <>
      {raw('<!doctype html>')}
      <html lang="en">
        <head>
          <meta charset="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <title>{title}</title>
          <link rel="stylesheet" href="/style.css" />
        </head>
        <body>
          <header>
            <a href="/">my-app</a>
          </header>
          <main>{children}</main>
        </body>
      </html>
    </>
  );
}

JSX can't express a doctype, and my first version shipped pages without one. raw() inserts it unescaped. Use raw() only for strings you wrote yourself.

src/ has no special meaning to Void, which makes it a good home for components. A page wraps its content in the layout:

// routes/index.tsx
import { defineHandler } from 'void';
import { Layout } from '../src/components/Layout';

const posts = [
  { slug: 'hello-void', title: 'Hello, Void' },
  { slug: 'no-framework', title: 'Rendering <without> a framework' },
];

export const GET = defineHandler((c) =>
  c.html(
    <Layout title="Home">
      <h1>Posts</h1>
      <ul>
        {posts.map((post) => (
          <li>
            <a href={`/posts/${post.slug}`}>{post.title}</a>
          </li>
        ))}
      </ul>
    </Layout>,
  ),
);

The response starts with <!doctype html><html lang="en">, and the second title came out as Rendering &lt;without&gt; a framework. JSX escapes text for you, which is the main reason I prefer it over strings.

The detail page reuses chapter 3's params validator, so params.slug is a checked string:

// routes/posts/[slug].tsx
import * as v from 'valibot';
import { defineHandler } from 'void';
import { Layout } from '../../src/components/Layout';

export const GET = defineHandler.withValidator({
  params: v.object({ slug: v.pipe(v.string(), v.regex(/^[a-z0-9-]+$/)) }),
})((c, { params }) =>
  c.html(
    <Layout title={params.slug}>
      <h1>{params.slug}</h1>
      <p>Rendered on the server with Hono JSX.</p>
    </Layout>,
  ),
);

Static files in public/

Files in public/ are served from the root as-is, without going through Vite's pipeline. I added a stylesheet:

/* public/style.css */
body { font-family: system-ui, sans-serif; max-width: 40rem; margin: 2rem auto; }

/style.css came back as text/css with cache-control: no-cache in dev. The build copied it to dist/client/.

Headers, redirects and rewrites

Rules that don't need code go in void.config.ts under routing:

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

export default defineConfig({
  routing: {
    typedRoutes: true,
    headers: {
      '/*': ['X-Frame-Options: DENY', 'X-Content-Type-Options: nosniff'],
      '/style.css': ['Cache-Control: public, max-age=3600'],
    },
    redirects: {
      '/old-home': '/',
      '/blog/*': { to: '/posts/:splat', status: 301 },
    },
    rewrites: {
      '/latest': '/posts/hello-void',
    },
  },
  worker: {
    compatibility_date: '2026-02-24',
  },
});

My first round of curls ignored all of it. The dev server reloaded the Worker but kept the old routing config. After a restart, everything applied:

  • / carried both security headers, and /style.css got cache-control: public, max-age=3600.
  • /old-home returned a 302 to / (a plain string means 302).
  • /blog/hello-void returned a 301 to /posts/hello-void, and /blog/a/b?x=1 kept its query string.
  • /latest served the hello-void page with a 200, and the address stayed /latest.

Each response in dev also carried an x-void-routing header naming the rule that fired, such as rewrite[/latest] -> /posts/hello-void (void.config.ts#routing.rewrites). That's the first place I look when a rule misbehaves. When the target depends on the request, the docs point you to c.redirect() and c.rewrite() in code instead.

What you're skipping

Void has three other ways to render, and this guide uses none of them. Here's what they are, from the docs, so you know what you're passing up:

  • Pages mode. Components in pages/ with React, Vue, Svelte or Solid, and a companion .server.ts exporting a loader for data and an action for forms. It's modeled on Inertia.js. The starter from chapter 2 was a pages app.
  • Islands. A page named *.island.tsx renders to static HTML, and only components imported with { island: 'load' } or 'visible' ship JavaScript.
  • Custom SSR. Your own src/main.ssr.tsx with defineRender() and a src/main.client.tsx that hydrates. You own the router and the HTML shell.

If your team lives in React, pages mode is the natural pick. For Datastar, plain routes returning HTML are all we need.

Chapter 5 gives these pages something real to render: the database.

The Database

D1 is Void's default database, Drizzle is bundled, and the CLI wraps the migration workflow, so you never install drizzle-kit yourself.

Everything in this chapter that shows output, I ran against Void 1.12.2 on Node 24.22.3 in a scratch app. The deploy-side pieces (drift stop, restore points, Hyperdrive) I took from the docs, and I'll say so when we get there.

The schema file

Your tables live in db/schema.ts. Column helpers come from void/schema-d1, and sql comes from void/db. You don't add Drizzle to package.json.

// db/schema.ts
import { sql } from "void/db";
import { integer, sqliteTable, text } from "void/schema-d1";

export const notes = sqliteTable("notes", {
  id: integer("id").primaryKey({ autoIncrement: true }),
  title: text("title").notNull(),
  body: text("body").notNull().default(""),
  createdAt: text("created_at").notNull().default(sql`(datetime('now'))`),
});

A long schema can be split into db/schema/*.ts and re-exported.

Querying through @schema

Import tables from @schema. That's a Vite alias the Void plugin sets up for you, pointing at db/schema.ts (or the db/schema/ folder). Import db and the query operators from void/db.

// routes/api/notes/index.ts
import { notes } from "@schema";
import { defineHandler } from "void";
import { db, desc } from "void/db";
import { createInsertSchema } from "void/drizzle-zod";

const insertNote = createInsertSchema(notes, {
  title: (schema) => schema.trim().min(1).max(200),
}).pick({ title: true, body: true });

export const GET = defineHandler(async () => {
  return db.select().from(notes).orderBy(desc(notes.id)).limit(10);
});

export const POST = defineHandler.withValidator({ body: insertNote })(
  async (_c, { body }) => {
    const [created] = await db.insert(notes).values(body).returning();
    return created;
  },
);

createInsertSchema builds a Zod validator from the table. I posted one good note and one blank title:

curl -X POST localhost:5173/api/notes \
  -H 'content-type: application/json' \
  -d '{"title":"From curl","body":"hi"}'
# {"id":6,"title":"From curl","body":"hi","createdAt":"2026-12-01 16:30:49"}

curl -X POST localhost:5173/api/notes \
  -H 'content-type: application/json' -d '{"title":"   "}'
# 400 {"error":"Validation failed","issues":[{"slot":"body","issues":[...]}]}

The trimmed blank title never reached D1.

Generate, migrate, status

The schema says what you want. Migrations are the SQL that gets you there. The loop is three commands:

npx void db generate   # write SQL into db/migrations/
npx void db migrate    # apply pending files to the local D1
npx void db status     # list applied and pending files

After adding the notes table, generate wrote a timestamped file with the CREATE TABLE you'd expect, and status showed both migrations as pending until I ran migrate:

●   20261201162856_third_beyonder.sql  local: applied
    20261201162921_black_famine.sql  local: applied
2 migrations

Read every generated file before you commit it. A rename can come out as a drop and an add.

Seeding with defineSeed

db/seed.ts exports a seed built with defineSeed. The context hands you a Drizzle db and your schema exports.

// db/seed.ts
import { defineSeed } from "void/seed";

export default defineSeed<typeof import("./schema")>(async ({ db, schema }) => {
  await db.insert(schema.notes).values(
    Array.from({ length: 5 }, (_, i) => ({
      title: `Note ${i + 1}`,
      body: "Seeded locally",
    })),
  );
});
npx void db seed --yes
# ◇ Reset database. Applied 2 migrations.
# ✓ Seeded from db/seed.ts.

Look at the first line of that output. seed wipes the local database first, then re-applies migrations, then runs your file. It's a reset button with sample data on top. --yes skips the prompt, which you'll want in scripts.

Looking at the data

void db execute runs SQL against the local database and prints a table. Add --json when a script needs the rows.

npx void db execute "SELECT id, title FROM notes LIMIT 3"
npx void db execute --json "SELECT count(*) AS total FROM notes"

The JSON is an array with results, success and meta per statement, the same shape as wrangler d1 execute --json. --remote targets the deployed database; I didn't run that.

npx void db studio opens Drizzle Studio. Mine came up at https://local.drizzle.studio. For D1 there's no --remote Studio; the docs point you at execute --remote.

Push is for throwaway databases

void db push applies the schema directly, no migration files. It's handy in the first hour of a project. Then it bit me.

I added a pinned column to a database that already had migrations applied and ran push. Drizzle warned that it was about to delete the _void_migrations table, which is how Void tracks what it applied. My shell had no TTY, so the confirmation prompt crashed. And the CLI still printed ✓ Database schema pushed. The column wasn't there.

My rule now: a database is either a push database or a migrate database. To switch, run npx void db reset --yes and start clean.

Status doesn't flag drift

The docs table describes void db status as checking "schema drift and pending migrations." On 1.12.2 it didn't catch mine. With pinned in the schema and no migration for it, status listed two applied files and said nothing else.

Drift checking happens at deploy time. The deploy reference says void deploy does a read-only drift check on Drizzle projects, and if a new migration would be generated, it stops and tells you to run void db generate, review the SQL, commit it, and deploy again. I didn't deploy for this chapter, so that part is from the docs. Locally, run generate yourself and see whether it writes a file.

The binding writes itself

I never declared a D1 binding or copied a database ID, and the generated .void-wrangler.jsonc stayed {}. Miniflare's local explorer still listed a DB binding on my Worker, because Void saw import { db } from "void/db".

That's resource inference: Void scans your source folders for imports like void/db. Per the docs, deploy provisions the real D1 and records it in void.lock.json, which you commit. To use an existing database, declare it under cloudflare.d1_databases in void.config.ts.

Deploys run your migrations

From the deployment guide (not run here): void deploy applies pending files in db/migrations/ before the new code goes live. --skip-migrations turns that off when another step owns migrations.

Rollback restores code only. If a migration dropped a column, older code that reads it breaks after a rollback, so keep each schema change compatible with the previous release.

D1 restore points

When you deploy D1 to your own Cloudflare account, the docs say deploy saves a restore point before running migrations and prints a void db restore command. It uses D1 Time Travel:

npx void db restore --bookmark <bookmark-from-deploy-output>
npx void db restore --timestamp 2026-10-16T09:30:00Z

Time Travel keeps 7 days of history on Workers Free and 30 on Workers Paid. A restore throws away every write after that point, and it rewinds migration history too, so the next deploy reapplies the files. The documented recovery order is: roll back the code with void project rollback if the live version needs the newer schema, restore the database, then fix the bad migration before deploying again. I'd paste that bookmark into the PR description every time.

Postgres and MySQL through Hyperdrive

The same Drizzle workflow covers PostgreSQL and MySQL. Set database: "pg" (or "mysql") in void.config.ts, import helpers from void/schema-pg or void/schema-mysql, and put DATABASE_URL in .env for local work. In production, Void creates a Cloudflare Hyperdrive config from your connection string so Workers reuse pooled connections. For a direct Cloudflare deploy, DATABASE_URL comes from the shell or CI that runs void deploy.

I haven't run any of this; it's from the database guides.

Next: KV, storage, and environment, where the same inference trick hands you a cache, a bucket and typed config.

KV, Storage, and Environment

The database holds your records. Everything else (cached settings, uploaded files, API keys) needs somewhere to live too. Void covers those with void/kv, void/storage and void/env, and it infers the bindings the same way it did for D1.

I ran the KV, R2 and env examples below against Void 1.12.2 on Node 24.22.3, with curl against the dev server. The void secret commands talk to a real Cloudflare account, so I didn't run those. That section is from the docs.

KV with void/kv

kv from void/kv stores JSON. You put an object in, you get the same object back.

import { kv } from "void/kv";

await kv.put("settings:page-size", 20);
const pageSize = await kv.get<number>("settings:page-size"); // number | null

For anything with more than one key, I reach for kv.map(). It gives you a typed client with its own key prefix:

// routes/api/prefs/[user].ts
import { defineHandler } from "void";
import { kv } from "void/kv";

type Prefs = { theme: "light" | "dark"; pageSize: number };

const prefs = kv.map<Prefs>("prefs");

export const GET = defineHandler(async (c) => {
  const value = await prefs.get(c.req.param("user") ?? "");
  return value ?? { theme: "light", pageSize: 20 };
});

export const PUT = defineHandler(async (c) => {
  const body = await c.req.json<Prefs>();
  await prefs.put(c.req.param("user") ?? "", body, { ttl: 60 * 60 * 24 * 30 });
  return { saved: true };
});

(The ?? "" is there because typed routes give param() a string | undefined type, and tsc complained without it.)

curl -X PUT localhost:5173/api/prefs/alice \
  -H 'content-type: application/json' -d '{"theme":"dark","pageSize":50}'
# {"saved":true}
curl localhost:5173/api/prefs/alice
# {"theme":"dark","pageSize":50}

The stored key is prefs:alice. Listing through the map strips the prefix, so kv.map("prefs").list() returned ["alice"] while kv.list({ prefix: "prefs:" }) returned ["prefs:alice"].

TTL has a floor

ttl is in seconds. I tried 30 and got this back from the local runtime:

KV PUT failed: 400 Invalid expiration_ttl of 30. Expiration TTL must be at least 60.

60 worked. If you want something to expire in 10 seconds, KV is the wrong tool. Store a timestamp in the value and check it on read, or use D1.

Also keep KV's consistency model in mind. Cloudflare documents KV as eventually consistent, so a write in one location can take a while to show up in another. Preferences and caches are fine. Counters and anything you'd check permissions against belong in the database.

Restart after a new binding

This one cost me a few minutes. I added the first void/kv import while the dev server was running. Vite reloaded the route, and every request failed with:

Error: env: Missing Cloudflare binding 'KV'.

Inference runs when the dev server starts. After I restarted it, the binding was there. Any time you add a new kind of resource (KV, storage, a queue), restart the dev server. Editing code that uses an existing binding hot-reloads fine.

Files in R2 with void/storage

storage from void/storage is the R2 bucket API with the binding filled in. Here's an upload route that takes a multipart form:

// routes/api/files/index.ts
import { defineHandler } from "void";
import { storage } from "void/storage";

export const POST = defineHandler(async (c) => {
  const form = await c.req.formData();
  const file = form.get("file");
  if (!(file instanceof File)) return c.json({ error: "file is required" }, 400);

  const key = `uploads/${crypto.randomUUID()}`;
  await storage.put(key, file, {
    httpMetadata: { contentType: file.type || "application/octet-stream" },
    customMetadata: { originalName: file.name },
  });
  return { key, size: file.size };
});

The server picks the key. Never let a client choose the path it writes to.

Downloads stream the object back. The nosniff and attachment headers come straight from the storage guide, and I agree with them: a user can upload HTML, and you don't want it running as a page on your domain.

// routes/api/files/[id].ts
import { defineHandler } from "void";
import { storage } from "void/storage";

export const GET = defineHandler(async (c) => {
  const object = await storage.get(`uploads/${c.req.param("id")}`);
  if (!object) return c.notFound();

  const headers = new Headers();
  object.writeHttpMetadata(headers);
  headers.set("etag", object.httpEtag);
  headers.set("X-Content-Type-Options", "nosniff");
  headers.set("Content-Disposition", "attachment");
  return new Response(object.body, { headers });
});

The round trip:

curl -X POST localhost:5173/api/files -F "file=@hello.txt;type=text/plain"
# {"key":"uploads/46ad288f-cbed-4ffc-b530-db41f564673f","size":14}

curl -i localhost:5173/api/files/46ad288f-cbed-4ffc-b530-db41f564673f
# HTTP/1.1 200 OK
# content-disposition: attachment
# content-type: text/plain
# x-content-type-options: nosniff
#
# hello from r2

A missing key gave a 404 and a form without file gave a 400.

Typed config with env.ts

Declare every variable your app reads in a root env.ts:

// env.ts
import { defineEnv, number, string, url } from "void/env";

export default defineEnv({
  API_TOKEN: string(),
  PAGE_SIZE: number().default(20),
  VITE_SITE_URL: url().default("https://mysite.com"),
});

Then read values through env from void/env. They come back typed: PAGE_SIZE=50 in .env arrived in my route as the number 50.

import { env } from "void/env";

const size = env.PAGE_SIZE; // number

npx void env check validates your local values. With no .env it listed API_TOKEN as missing. With PAGE_SIZE=lots it printed Expected a number, got "<redacted>" and exited 1. Values are masked by default, which is what you want when this runs in CI logs.

If you skip the check, the dev server still starts. Then every request returns a 500 with Env validation failed at worker boot: API_TOKEN is required but missing. Loud, at least.

One .env, at the root

Void reads exactly one local file: .env in the project root. I created .env.local to see what happens:

■ env: only .env is supported for local development. Remove .env.local

It also rejected a .env.bak I'd left lying around during testing. Any .env.* sibling trips it. Keep backups somewhere else.

One confusing detail: when a key was missing, the Cloudflare Vite plugin printed its own hint suggesting .dev.vars or .env.local. Ignore that message. Void's rule wins.

Production secrets

From the env and secrets docs (not run here): every non-VITE_ key in env.ts is a server value, stored as an encrypted Worker secret in production.

npx void secret put API_TOKEN                     # prompts with masked input
npx void secret sync /secure/path/production.env  # bulk upload from a file outside the repo
npx void secret list                              # names only, never values
npx void secret delete API_TOKEN

Values are validated against env.ts before upload. void deploy never uploads .env, and it refuses to deploy if a required server key is missing remotely. sync keeps existing remote secrets that aren't in the file.

VITE_ values are public

Keys starting with VITE_ are client values. They get baked into browser JavaScript, so they're never secrets. Read them with import.meta.env.VITE_SITE_URL in client code.

The part that surprised me: builds ignore VITE_* values in .env. I had VITE_SITE_URL set to my localhost dev URL in .env and ran vite build. The bundle contained the schema default, https://mysite.com. Then I ran VITE_SITE_URL=https://example.com npx vite build and the bundle had https://example.com.

That's deliberate. Your laptop's localhost URL can't leak into production by accident. Set client values in the build shell or in CI, or give them a safe default in env.ts.

Next: auth, where Void wires Better Auth into the same database and gives you requireAuth for your routes.

Auth

Void wraps Better Auth. You get sign-up, sign-in, sessions and a requireAuth helper, with the auth tables living in the same D1 database as your app. You don't run an auth service, and local dev needs no secret.

I tested this chapter against Void 1.12.2 on Node 24.22.3 with curl: a full sign-up, sign-in and sign-out round trip, a protected route, a custom auth.ts, and a GitHub provider with fake credentials. I did not finish a real OAuth login, so anything past the provider redirect is from the docs.

Native apps only

Void-managed auth works in native Void apps on Cloudflare. If you run Void in framework mode (Astro, SvelteKit, Nuxt and friends) or on Node, Bun or Deno, the docs tell you to use Better Auth directly. Pick this up before you choose a framework, because it's one of the things you give up.

Turning it on

There's no install step. Auth switches on when you import anything from void/auth, import auth from void/client, add auth to void.config.ts, or create a root auth.ts.

The first time I started the dev server with a void/auth import, the log said [void] Applied Better Auth migrations and four new tables showed up in the local database: user, session, account and verification. Email and password is on by default.

Protecting a route

requireAuth(c) returns the signed-in user or throws a 401.

// routes/api/me.ts
import { defineHandler } from "void";
import { requireAuth } from "void/auth";

export const GET = defineHandler((c) => {
  const user = requireAuth(c);
  return { id: user.id, email: user.email, name: user.name };
});

For pages, pass throwRedirect and signed-out visitors get bounced:

// routes/account/index.ts
import { defineHandler } from "void";
import { requireAuth } from "void/auth";

export const GET = defineHandler((c) => {
  const user = requireAuth(c, { throwRedirect: "/login" });
  return c.html(`<h1>Hi ${user.name}</h1>`);
});

A signed-out GET /account returned 302 to /login. The docs say non-GET requests get a 303.

When signing in is optional, use getUser() or getSession(). Neither takes the context; they read the current request's auth state.

// routes/api/whoami.ts
import { defineHandler } from "void";
import { getSession, getUser } from "void/auth";

export const GET = defineHandler(() => {
  const user = getUser();
  const state = getSession();
  return {
    signedIn: user !== null,
    email: user?.email ?? null,
    expiresAt: state?.session.expiresAt ?? null,
  };
});

Sync or await?

The docs disagree with themselves. The auth guide and API reference call requireAuth(c) without await. The SSE guide has const user = await requireAuth(c).

I checked both. The type declaration in 1.12.2 is requireAuth(c, options?): AuthUser. It's synchronous. I ran a route with each form, signed in, and both returned the same user. await on a plain value is a no-op, so the SSE example works, and TypeScript doesn't complain about it either.

Use the sync form. It matches the signature, and it lets your handler stay non-async when it has nothing else to wait for.

A round trip with curl

The client in void/client calls Better Auth's endpoints under /api/auth. I hit those directly so you can see what goes over the wire.

curl -c jar.txt -X POST localhost:5173/api/auth/sign-up/email \
  -H 'content-type: application/json' \
  -H 'origin: http://localhost:5173' \
  -d '{"email":"alice@example.com","password":"example-password-123","name":"Alice"}'

curl -b jar.txt localhost:5173/api/me
# {"id":"ypjzh20u...","email":"alice@example.com","name":"Alice"}

Sign-up also signs you in. Then I tried sign-in from a fresh cookie jar, a wrong password, and sign-out:

curl -c jar2.txt -X POST localhost:5173/api/auth/sign-in/email \
  -H 'content-type: application/json' -H 'origin: http://localhost:5173' \
  -d '{"email":"alice@example.com","password":"example-password-123"}'
# 200, sets the session cookie

# wrong password
# 401 {"message":"Invalid email or password","code":"INVALID_EMAIL_OR_PASSWORD"}

curl -b jar2.txt -c jar2.txt -X POST localhost:5173/api/auth/sign-out \
  -H 'origin: http://localhost:5173' -H 'content-type: application/json' -d '{}'
# {"success":true}, and /api/me goes back to 401

Notice the origin header on every POST. Without it, Better Auth answered 403 MISSING_OR_NULL_ORIGIN. With origin: https://evil.example, it answered 403 INVALID_ORIGIN. Browsers send Origin on their own, so this only bites in scripts and tests. A five-character password got 400 PASSWORD_TOO_SHORT.

Sessions and cookies

The session lives in one cookie:

set-cookie: better-auth.session_token=...; Max-Age=604800; Path=/; HttpOnly; SameSite=Lax

That's seven days, HttpOnly, SameSite=Lax. On plain-HTTP localhost there was no Secure flag. A signed-in request to my notes API came back with cache-control: no-store; the same request signed out had no cache header. Void adds that so a shared cache never stores one user's page for another.

From the docs: Void creates BETTER_AUTH_SECRET on your first deploy and reuses it after that. Deployed apps also get Better Auth's per-IP rate limits (3 sign-in attempts per 10 seconds by default), counted per Worker instance unless you move the count into the database.

Customizing with defineAuth

For anything past the defaults, add a root auth.ts. Spread defaults yourself; Void doesn't deep-merge.

// auth.ts
import { defineAuth } from "void/auth";

export default defineAuth(({ defaults }) => ({
  ...defaults,
  emailAndPassword: {
    ...defaults.emailAndPassword,
    enabled: true,
    minPasswordLength: 12,
  },
  session: {
    ...defaults.session,
    expiresIn: 60 * 60 * 24 * 30,
  },
}));

After a restart, a 10-character password got PASSWORD_TOO_SHORT, and a good sign-up set Max-Age=2592000. Thirty days. Both changes took.

Adding providers

Social logins go in void.config.ts:

// void.config.ts
import { defineConfig } from "void/config";

export default defineConfig({
  auth: { providers: ["email", "github"] },
});

Credentials come from AUTH_GITHUB_CLIENT_ID and AUTH_GITHUB_CLIENT_SECRET (the pattern is AUTH_<PROVIDER>_...). I added github before setting them. Every route in the app returned 500, including my unrelated notes API, with auth: Missing credentials for provider 'github'. The auth middleware runs on every request, so a missing provider credential takes the whole app down.

With placeholder values in .env, POST /api/auth/sign-in/social with {"provider":"github"} returned a GitHub authorize URL with redirect_uri set to /api/auth/callback/github. That's as far as I went without a real OAuth app.

Auth tables and migrations

Locally, the dev server creates auth tables for you. A direct Cloudflare deploy needs them in your checked-in migrations, so run npx void db generate. Mine produced a migration with all four CREATE TABLE statements.

Then npx void db migrate failed: table account already exists. The dev server had already made those tables. The fix was npx void db reset --yes, which rebuilt the local database from the migration files. After that, the dev server started cleanly and sign-up worked again.

To reference users from your own tables, import userTable from @auth-schema and point a foreign key at userTable.id. The IDs are text by default.

Next: background work, where crons, queues and workflows run code after the response has already gone out.

Background Work

Some work shouldn't happen inside a request. Cleanup at 3 a.m., a welcome email after sign-up, a post that publishes tomorrow morning. Void gives you three folders for that: crons/, queues/ and workflows/.

I ran the cron and queue examples below against Void 1.12.2 on Node 24.22.3, triggering both locally. Workflows are a different story, and I'll get to why.

Cron jobs in crons/

Each file in crons/ exports a cron expression and a default handler wrapped in defineScheduled.

// crons/heartbeat.ts
import { defineScheduled } from "void";
import { kv } from "void/kv";

export const cron = "*/15 * * * *";

export default defineScheduled(async (controller) => {
  await kv.put("jobs:last-heartbeat", new Date(controller.scheduledTime).toISOString());
  console.log(`heartbeat ran for ${controller.cron}`);
});

Handlers can use the same void/* modules as routes. Here's a nightly cleanup against the notes table from chapter 5:

// crons/nightly.ts
import { notes } from "@schema";
import { defineScheduled } from "void";
import { db, lt } from "void/db";

export const cron = "0 3 * * *";

export default defineScheduled(async () => {
  const cutoff = new Date(Date.now() - 30 * 86_400_000).toISOString();
  const deleted = await db.delete(notes).where(lt(notes.createdAt, cutoff)).returning();
  console.log(`nightly cleanup removed ${deleted.length} notes`);
});

cron can also be an array of expressions. Files starting with _ are skipped.

Triggering a cron locally

Schedules don't fire in dev. You trigger them by hand. When the dev server starts and finds cron files, it prints a ready-made command:

[void] Detected 2 crons. Trigger locally:
  curl -X POST http://localhost:5173/__void/scheduled \
    -H "x-void-dev-trigger: <token>" \
    -d '{"cron":"*/15 * * * *","scheduledTime":'"$(date +%s000)"'}'

The token also lives in .void/dev-trigger-token, so a script can read it:

TOKEN=$(cat .void/dev-trigger-token)
curl -X POST localhost:5173/__void/scheduled \
  -H "x-void-dev-trigger: $TOKEN" \
  -d '{"cron":"*/15 * * * *","scheduledTime":'"$(date +%s000)"'}'
# {"ok":true}

Before the trigger, my heartbeat route read null from KV. After it, the timestamp was there and the dev log had heartbeat ran for */15 * * * *. The nightly job logged nightly cleanup removed 0 notes, because the seed data was minutes old.

Two things I hit. No token gives 401 {"error":"unauthorized"}, as it should. A cron expression that no file exports also returns {"ok":true} and runs nothing. A typo in the expression looks like success. Copy the expression from the file, or check the log line.

In production, native scheduled events need no token; Cloudflare calls the handler. When you deploy to your own account, Cloudflare's Cron Trigger limits apply. That part is from the jobs guide.

Queues in queues/

A queue is a file in queues/ with a default export wrapped in defineQueue<T>. The path names the queue: queues/emails.ts becomes emails, and the binding becomes QUEUE_EMAILS. The generic types both the consumer and every send() call.

// queues/emails.ts
import { defineQueue } from "void";
import { kv } from "void/kv";

export interface EmailJob {
  id: string;
  to: string;
  subject: string;
}

export const maxBatchSize = 10;
export const maxRetries = 3;

export default defineQueue<EmailJob>(async (batch) => {
  for (const msg of batch.messages) {
    const doneKey = `emails:sent:${msg.body.id}`;
    if (await kv.get(doneKey)) {
      msg.ack();
      continue;
    }
    try {
      if (msg.body.to.endsWith("@fail.test")) throw new Error("provider down");
      console.log(`[emails] sending "${msg.body.subject}" to ${msg.body.to} (attempt ${msg.attempts})`);
      await kv.put(doneKey, true, { ttl: 60 * 60 * 24 * 7 });
      msg.ack();
    } catch (err) {
      console.log(`[emails] attempt ${msg.attempts} failed for ${msg.body.id}: ${err}`);
      if (msg.attempts > maxRetries) {
        await kv.put(`emails:failed:${msg.body.id}`, { ...msg.body, error: String(err) });
        msg.ack();
      } else {
        msg.retry({ delaySeconds: 5 });
      }
    }
  }
});

The @fail.test check is there only so I could watch retries. Swap in your real email call. The emails:failed: branch is explained below.

Sending goes through the typed queues proxy from void/queues:

// routes/api/signup-email.ts
import { defineHandler } from "void";
import { queues } from "void/queues";

export const POST = defineHandler(async (c) => {
  const { email } = await c.req.json<{ email: string }>();
  const id = crypto.randomUUID();
  await queues.emails.send({ id, to: email, subject: "Welcome aboard" });
  return c.json({ queued: id }, 202);
});

My first send failed with Missing Cloudflare binding 'QUEUE_EMAILS'. Same rule as KV in chapter 6: a new resource needs a dev server restart. After restarting, the dev server listed 1 queue next to the crons.

curl -X POST localhost:5173/api/signup-email \
  -H 'content-type: application/json' -d '{"email":"dana@example.com"}'
# 202 {"queued":"912cdae2-..."}

The route answered right away, and the consumer logged sending "Welcome aboard" to dana@example.com (attempt 1). In native apps, a local send invokes the consumer in Miniflare with the same handler you'd deploy.

Retries, and no dead-letter queue

Before I added the emails:failed: branch, I sent a message to erin@fail.test. With maxRetries = 3, the log showed attempts 1 through 4, five seconds apart, and then nothing. The message was gone.

That's the production behavior too, per the queues guide: Void-managed queues don't configure a dead-letter queue, and Cloudflare permanently deletes a message once it exhausts its retries. So design for it:

  • Make every consumer idempotent. Queues deliver at least once. My emails:sent:<id> key in KV means a redelivered message gets acked without a second email. Put the ID in the message body so the key is stable across retries.
  • Record your own failures. With maxRetries = 3, the fourth attempt is the last, and msg.attempts > maxRetries is true on it. That's where the consumer above writes the body to emails:failed:<id> and acks. I sent gus@fail.test with that code in place: four failed attempts, then kv.map("emails:failed").list() returned his message with "error":"Error: provider down". For anything you need to query or replay in bulk, use a D1 table instead of KV. Either way, that's your dead-letter queue.
  • Back off. msg.retry({ delaySeconds }) or the retryDelay export keeps you from hammering a provider that's already down.

If a message has no explicit ack() or retry(), Void acks it when the handler returns and retries it when the handler throws.

Dispatching a batch by hand

The dev server also exposes /__void/queue, so you can replay a specific message. I re-sent Dana's message ID next to a new one:

curl -X POST localhost:5173/__void/queue \
  -H "content-type: application/json" \
  -H "x-void-dev-trigger: $TOKEN" \
  -d '{"queue":"emails","messages":[
    {"id":"1","timestamp":'"$(date +%s000)"',"body":{"id":"912cdae2-...","to":"dana@example.com","subject":"Welcome aboard"},"attempts":1},
    {"id":"2","timestamp":'"$(date +%s000)"',"body":{"id":"manual-1","to":"finn@example.com","subject":"Manual"},"attempts":1}]}'
# {"ok":true,"decisions":{"1":{"action":"ack"},"2":{"action":"ack"}}}

Both were acked. Only Finn's produced a send in the log; the duplicate hit the idempotency key and stopped. The decisions map is handy in tests.

From the docs: on a direct Cloudflare deploy, queue names get the Worker name prefixed (my-app-emails) and must fit in 63 characters. Your code still calls queues.emails.send().

Workflows: documented, not released

The docs site has a Workflows guide. A file in workflows/ default-exports defineWorkflow() from void/workflows, with a run(event, step, ctx) method, and a route starts it:

// Adapted from the docs example. This does not run on Void 1.12.2.
import { defineWorkflow } from "void/workflows";

export default defineWorkflow<{ slug: string; publishAt: string }>({
  async run({ payload }, step, { env }) {
    await step.sleepUntil("publication time", new Date(payload.publishAt));
    await step.do("publish post", () => env.KV.put(`posts:${payload.slug}`, "live"));
    return { slug: payload.slug };
  },
});

On 1.12.2 it doesn't exist. I created that file and a route that called .create(), and the dev server failed with "./workflows" is not exported ... from package void. Importing void/workflows from Node gave ERR_PACKAGE_PATH_NOT_EXPORTED. The package's export map has no ./workflows entry.

The feature landed on the main branch on 2026-12-01 (PR #918, "add Cloudflare Workflows through a workflows/ convention"). The docs at void.cloud track main; the npm release doesn't have it yet. I'll test it in this chapter once it ships in a tagged version. Until then, a queue with delaySeconds or a cron that sweeps a "publish at" column covers most delayed work.

Per the unreleased docs, each step is retried on its own and completed steps are skipped on resume, so side effects belong inside step.do(). Workers Free includes Workflows, with paid plans needed for things like more than 1,024 steps or retention past 3 days.

Next: Realtime: SSE, Live, WebSockets, and Durable State, where the server stops waiting for the browser to ask.

Realtime: SSE, Live, WebSockets, and Durable State

Void gives you four ways to push data at a browser or hold shared state. They overlap just enough to be confusing, so I built one of each in a scratch app on Void 1.12.2 and poked at them with curl and a Node WebSocket client until I knew where the edges were.

Short version: void/sse for one request streaming its own output, void/live for fanout across many requests, .ws.ts rooms for two-way chat, and void/durable for state that outlives any single connection.

One request, one stream: void/sse

eventStream() returns a Response right away and hands you a stream object. Here's the route I tested:

// routes/api/events.ts
import { defineHandler } from 'void';
import { eventStream } from 'void/sse';

export const GET = defineHandler((c) => {
  return eventStream(
    async (stream) => {
      await stream.comment('connected');
      await stream.send({ event: 'ready', data: { now: Date.now() } });
      await stream.send({ event: 'html', data: '<li>one</li>\n<li>two</li>' });

      let n = 0;
      const timer = setInterval(() => {
        stream.send({ event: 'tick', data: { n: ++n } }).catch(() => stream.close());
      }, 1000);

      await stream.closed;
      clearInterval(timer);
      console.log(`[events] client left after ${n} ticks`);
    },
    { signal: c.req.raw.signal, keepAlive: { intervalMs: 3000, comment: 'ping' } },
  );
});

The part people get wrong is await stream.closed. When the start callback returns, Void closes the stream. If you set up a timer and fall off the end of the function, the client gets one burst and a hangup. Waiting on stream.closed keeps it open until the client leaves.

I ran curl -N against it for 7 seconds:

: connected

event: ready
data: {"now":1796142600376}

event: html
data: <li>one</li>
data: <li>two</li>

event: tick
data: {"n":1}

event: tick
data: {"n":2}

: ping

A few things in there are worth knowing. Objects get JSON-encoded for you. The keepalive is a plain SSE comment (the default is every 15 seconds; I dropped it to 3 to see it). And when curl gave up, the server log printed [events] client left after 7 ticks, so passing the request's signal really does resolve stream.closed on disconnect.

Look at the html event. A string with a newline got split into two data: lines. That's correct SSE, and the browser's EventSource joins them back with \n. The docs don't mention it, though, and it matters a lot once you send HTML fragments to something like Datastar, which wants its own prefix on every line. Chapter 14 deals with that head on.

formatSseText() does the same splitting when you format a frame yourself. I checked it directly in Node:

formatSseText({ event: 'patch', data: '<div>\n  hi\n</div>' })
=> "event: patch\ndata: <div>\ndata:   hi\ndata: </div>\n\n"

Last check: writing after close. I closed a stream and then called send(). It threw, and the error's name was SseStreamClosedError. That's why the interval above catches and calls close() instead of letting the rejection float.

Fanout: void/live

SSE from a single handler can't hear what other requests are doing. void/live fixes that with topics, backed by Durable Objects. You define a stream once and expose it from a route:

// src/live.ts
import { defineLiveStream } from 'void/live';

export const live = defineLiveStream({ id: 'app', allowAnonymousControl: true });
// routes/live.ts
import { defineHandler } from 'void';
import { live } from '../src/live';

export const GET = defineHandler((c) => live.connect(c));
export const POST = defineHandler((c) => live.control(c));

Then publish from anywhere server-side:

await live.publish('post:12', { title }, { type: 'updated', eventId: `v${Date.now()}` });

It worked in local dev. I opened two raw SSE connections, subscribed both to post:12 with a POST to /live, then published once to post:12 and once to post:99. Both connections got exactly one event:

event: message
data: {"subscriptionId":"card","topic":"post:12","type":"updated","eventId":"v1796142636929","data":{"title":"Hello\nworld"}}

Two things surprised me. The connectionId has to be a UUID; tab-a got 400 live: invalid connectionId. And every event arrives as event: message with Void's own JSON envelope, never a native SSE id. The browser helper, connectLiveStream() from void/live/client, unwraps that envelope and restores subscriptions after a reconnect. If you consume the stream any other way, you're parsing the envelope yourself.

The limits are the real design constraint. From the docs (I didn't load-test these):

  • 256 active subscriptions per topic, and you can lower it but not raise it
  • 256 subscriptions per browser connection
  • 100 queued events per connection
  • 64 KiB per encoded event
  • at-most-once delivery, ordered within a topic

Deploys, rollbacks and restarts can drop live state. So treat void/live as a doorbell. Store the real data in D1 and use eventId/lastEventId to catch up. Also add onSubscribe before you publish anything private, because without it any allowed connection can read any topic.

Two-way: .ws.ts rooms

A file like routes/rooms/[room].ws.ts gives each room its own Durable Object. I used zod for the message schemas since any Standard Schema library works:

// routes/rooms/[room].ws.ts
import { z } from 'zod';
import { defineRoom } from 'void/ws';

const ClientMessage = z.object({ type: z.literal('chat.message'), text: z.string() });
const ServerMessage = z.discriminatedUnion('type', [
  z.object({ type: z.literal('chat.message'), from: z.string(), text: z.string() }),
  z.object({ type: z.literal('chat.joined'), id: z.string() }),
]);

export default defineRoom({
  messages: { client: ClientMessage, server: ServerMessage },
  async onConnect(ctx) {
    await ctx.room.broadcast({ type: 'chat.joined', id: ctx.connection.id }, [ctx.connection.id]);
  },
  async onMessage(ctx, event) {
    await ctx.room.broadcast({ type: 'chat.message', from: ctx.connection.id, text: event.text });
  },
});

With two Node WebSocket clients on /rooms/general, Alice's message reached both of them. Then I got rude. A plain-text frame closed the socket with code 1007 Invalid JSON. A JSON message that failed the schema closed it with 1007 Invalid message. Validation is strict: a bad frame gets the client disconnected. A plain HTTP GET to the same path returned 426.

defineWebSocket() is the per-connection version for things like notifications. I only ran the room.

Shared state: void/durable

Durable State is a typed Durable Object with methods:

// durable-objects/counter.ts
import { defineDurableState } from 'void/durable';

export const Counter = defineDurableState({
  initialState: { count: 0 },
  methods: {
    increment(context, amount: number) {
      context.state.count += amount;
      return context.state.count;
    },
    read(context) {
      return context.state.count;
    },
  },
});

export default Counter;

A route calls Counter.get(name).increment(1). Two POSTs to alpha gave 1 then 2, beta started at 1, and after I restarted the dev server alpha still read 2. Methods run one at a time per name, which is what you want for a rate limiter or a board's version number.

Run void info before you rename anything. It printed the inferred name for both my counter (counter) and my room (rooms-room), and pinning that name is how you keep stored data across a file move.

Which one?

Need

Use

Watch out for

One request streams its own output (AI tokens, progress)

void/sse

Await stream.closed; multi-line data splits

Many requests push to many viewers

void/live

256 per topic, at-most-once, dropped on deploy

Browser talks back over the same socket

.ws.ts room

JSON only; bad frames close with 1007

Shared state under a name, no socket

void/durable

Pin name before moving files

Native apps only, for most of this. The docs say .ws.ts routes and custom Durable State modules don't work in framework mode. void/live isn't on the framework feature list either, so I'd treat it the same way. That's one reason the Part 2 app is a native Void app, and Chapter 18 builds its live board updates for Datastar on top of exactly these pieces.

Next up is the other thing everyone wants from a Worker: calling a model and sending email.

AI and Email

Two imports cover the "talk to the outside world" jobs: void/ai for models and void/email for mail. They behave very differently in local dev, and that difference shaped how I wrote this chapter.

Email runs fully offline. I sent mail, read it in a local inbox, and tested both directions with Void's testing helpers.

AI doesn't. Workers AI has no local simulator, so the dev server calls Cloudflare for real, on your account. This guide's scratch work ran with no Cloudflare login, on purpose, so everything in the AI half of this chapter comes from the Void 1.12.2 docs, not from code I ran. Part 2 adds an AI feature to a deployed app and tests it there.

The void/ai surface

ai from void/ai wraps Cloudflare's AI binding. The basic call mirrors env.AI.run(), with model names and inputs typed from @cloudflare/workers-types:

// routes/api/ask.ts
import { defineHandler } from 'void';
import { ai } from 'void/ai';

export const POST = defineHandler(async (c) => {
  const { prompt } = await c.req.json();

  const result = await ai.run('@cf/meta/llama-3.3-70b-instruct-fp8-fast', {
    messages: [{ role: 'user', content: prompt }],
  });
  return c.json(result);
});

The rest of the API, per the docs:

  • ai.stream(model, inputs) returns a response with SSE headers that you can hand straight back from a handler. If generation dies after the response starts, the stream ends with a void:error event, or void:limit for a usage limit.
  • ai.image(model, { prompt }) for Cloudflare image models. ai.run() also returns binary output as a Blob.
  • ai.toMarkdown([{ name, blob }]) converts documents such as PDFs to Markdown.
  • ai.models({ task: 'Text Generation' }) lists what's available.
  • ai.provider('openai').fetch('/chat/completions', { body }) sends a provider-native request with your own key.

That last one is the escape hatch. The request keeps the provider's own HTTP shape but goes through Cloudflare AI Gateway. Keys follow a naming convention (OPENAI_API_KEY, GOOGLE_API_KEY), set in production with void secret put and locally in the root .env. For a provider Void doesn't know, you pass apiKeyEnv and apiKeyHeader yourself.

Third-party models also work through ai.run() with Cloudflare's model IDs, like google/gemini-2.5-flash, and AI Gateway options go in a third argument ({ gateway: { skipCache: true } }). On a direct Cloudflare deploy, provider-native requests need ai.gateway configured in your Void config.

Usage limits

Workers AI bills in neurons against your Cloudflare account. When something runs out, the promise rejects with UsageLimit from void/limits. In a route handler, an uncaught one becomes a structured HTTP 429 with retry info, which is a sensible default. In a queue consumer or cron job it's just a rejected promise, so catch it there.

If you want a friendlier message:

import { defineHandler } from 'void';
import { ai } from 'void/ai';
import { UsageLimit } from 'void/limits';

export const POST = defineHandler(async (c) => {
  const { prompt } = await c.req.json();
  try {
    const result = await ai.run('@cf/meta/llama-3.3-70b-instruct-fp8-fast', {
      messages: [{ role: 'user', content: prompt }],
    });
    return c.json(result);
  } catch (error) {
    if (error instanceof UsageLimit) {
      return error.response({ message: 'Try again shortly. Your prompt has been kept.' });
    }
    throw error;
  }
});

On the client, fetchStream() from void/client throws UsageLimit for limits and StreamError for other terminal errors. Catch both so the UI can stop its spinner and keep partial output.

The local dev catch

The docs are clear on this, and it's the thing I'd tape to my monitor. As soon as the app imports void/ai, Void turns on a remote Workers AI binding in dev and preview. You need void connect --platform cloudflare and a void cloudflare login session (or CLOUDFLARE_API_TOKEN), and every dev request spends your account's allowance. wrangler login doesn't count.

So I keep every AI call inside one small helper and mock void/ai in tests, which Chapter 11 shows. That won't stop the dev server from wanting a login (any import of void/ai turns the remote binding on), but my test suite never touches Cloudflare, and I only hit the real model when I mean to.

Sending email

sendEmail returns a result instead of throwing:

// src/welcome.ts
import { sendEmail } from 'void/email';

export async function sendWelcome(to: string) {
  const result = await sendEmail({
    from: 'Acme <hello@mail.example.com>',
    to,
    subject: 'Welcome aboard',
    text: 'Thanks for signing up.',
  });
  return result.ok;
}

A failed result has two shapes. result.error is a request-level failure; result.deliveries lists per-recipient failures. Check both. OUTCOME_UNKNOWN means the provider may already have the message, so don't blindly resend.

In dev this works with no account at all. Once the app imported void/email, the dev server printed an inbox URL on startup:

[void] Email inbox: http://localhost:5173/__void/inbox?token=<printed-token>

I POSTed to a route that called sendWelcome('user@example.com'), got {"ok":true}, and the message showed up in that inbox with its subject. Without the token header the inbox returned 401. The token lives in .void/dev-trigger-token, so treat it like a password if you expose the dev server.

One catch from the docs: the dev inbox works in native Void apps, TanStack Start and React Router. In Astro, SvelteKit, Nuxt and Analog, sends return BINDING_MISSING.

Receiving email

Inbound handlers live in a top-level email/ folder, and the filename matches the local part of the address. support.ts handles support@, support+[ticket].ts captures a tag, _default.ts catches the rest. This is native-app only.

// email/support.ts
import { defineEmail, parseEmail, replyEmail } from 'void/email';

export default defineEmail(async (message) => {
  const parsed = await parseEmail(message);
  if (parsed.subject?.startsWith('STOP')) {
    message.setReject('Use the unsubscribe link.');
    return;
  }
  await replyEmail(message, { text: 'Got it. We will reply within a day.' });
});

Call parseEmail() once per message; the underlying stream can only be read once.

Testing both directions

void/email/testing exports capture helpers for each direction. These ran under vp test with no mocks and no Worker:

// tests/email.test.ts
import { describe, expect, it } from 'vite-plus/test';
import { createEmailTestHarness, createInboundTestHarness } from 'void/email/testing';
import { sendWelcome } from '../src/welcome';
import support from '../email/support';

describe('email', () => {
  it('captures the welcome email', async () => {
    const inbox = createEmailTestHarness();
    expect(await sendWelcome('user@example.com')).toBe(true);
    expect(inbox.messages[0].subject).toBe('Welcome aboard');
    inbox.dispose();
  });

  it('replies to support mail and rejects STOP', async () => {
    const inbound = createInboundTestHarness({ slug: null, routes: { support } });
    const result = await inbound.deliver({
      from: 'user@example.com',
      to: 'support@mail.example.com',
      subject: 'Help',
      text: 'My board is empty',
    });
    expect(result.handler).toBe('support');
    expect(inbound.replies).toHaveLength(1);

    await inbound.deliver({
      from: 'user@example.com',
      to: 'support@mail.example.com',
      subject: 'STOP',
      text: 'bye',
    });
    expect(inbound.rejects).toEqual(['Use the unsubscribe link.']);
  });
});

slug: null means direct Cloudflare mail, with no platform project prefix.

The Workers Paid caveat

This one bites on your own Cloudflare account. From the docs: sending to arbitrary recipients needs Workers Paid plus Email Sending onboarding. On Workers Free, an app with email/ handlers can only send to verified destination addresses, and an app with no handlers can't send at all, because that path goes through Email Sending.

You also need email.from in void.config.ts on a domain your account can send from, plus SPF, DKIM and DMARC. void deploy --platform cloudflare walks you through the setup. I haven't run that part yet; Part 2 does.

With models and mail covered, the next question is how to test all of this without a Worker running. That's Chapter 11.

Testing and Local Dev

Void has two very different local environments, and most of my confusion early on came from mixing them up. The dev server runs your code inside a local Worker runtime with real (local) bindings. The test runner runs your code in plain Node with no Worker at all.

Once that clicked, the rest of this chapter fell into place.

What runs where

Dev server (npm run dev)

Tests (vp test)

Runtime

Local Worker via Miniflare

Node.js

D1, KV, R2

Local, file-backed

Not available, mock them

Durable State, live, .ws.ts

Local Durable Objects

Not available, mock them

Migrations

Applied on startup

Not applied

Email

Captured in the dev inbox

Captured by void/email/testing

Workers AI

Remote, on your account

Mock it

There's no void dev command, by the way. Some docs pages mention it, but in 1.12.2 void dev prints Unknown command 'dev'. The dev server is Vite's: npm run dev, which the starter maps to vp dev. On startup mine printed [void] Applied 1 migration(s) before anything else, so local D1 is always at your latest migration.

Local state survives restarts. In Chapter 9 my Durable State counter still read 2 after I killed and restarted the dev server. That's handy, and it also means stale local data can outlive a schema idea you abandoned. void db reset exists for that.

Running tests

A Vite+ starter has Vitest built in. Import from vite-plus/test and run:

vp test

In an interactive terminal Vitest watches by default. For a single pass (what CI wants) I ran vp test run. If you picked plain Vite during void init, install vitest and use it for both the imports and the command.

Put tests in tests/ or next to the code in src/. Keep them out of routes/, pages/ and the other convention folders, or Void treats them as part of the app. Imports like void/* and the @schema alias work in tests with no extra config. I checked @schema specifically, since it's an alias Void wires up.

Why everything needs a mock

Here's what happens if you call a binding from a test without mocking it. This function counts visits in KV:

// src/visits.ts
import { kv } from 'void/kv';

export async function countVisit(): Promise<number> {
  const visits = ((await kv.get<number>('visits')) ?? 0) + 1;
  await kv.put('visits', visits);
  return visits;
}

Called bare from a test, it fails with:

Error: env: Cloudflare env is unavailable. Use void runtime bindings inside
Nuxt/SvelteKit/Analog server request handlers or Worker handlers.

That's the Node-not-Worker split showing up. The fix is vi.mock() on the void/* module:

// tests/visits.test.ts
import { expect, it, vi } from 'vite-plus/test';
import { countVisit } from '../src/visits';

vi.mock('void/kv', () => {
  const values = new Map<string, unknown>();
  return {
    kv: {
      get: async (key: string) => values.get(key) ?? null,
      put: async (key: string, value: unknown) => {
        values.set(key, value);
      },
    },
  };
});

it('counts visits', async () => {
  await countVisit();
  expect(await countVisit()).toBe(2);
});

Mocking the database

void/db exports both the db client and Drizzle helpers like desc and eq. If you replace the whole module, you lose the helpers, and your schema file (which imports sql from void/db) breaks. So I spread the real module and swap only db:

// src/messages.ts
import { db, desc } from 'void/db';
import { messages } from '@schema';

export async function latestMessages(limit = 5) {
  return db.select().from(messages).orderBy(desc(messages.id)).limit(limit);
}
// tests/messages.test.ts
import { expect, it, vi } from 'vite-plus/test';
import { latestMessages } from '../src/messages';

const rows = [{ id: 2, text: 'second', createdAt: '2026-12-01' }];
const limit = vi.fn(async () => rows);

vi.mock('void/db', async (importOriginal) => ({
  ...(await importOriginal<typeof import('void/db')>()),
  db: {
    select: () => ({ from: () => ({ orderBy: () => ({ limit }) }) }),
  },
}));

it('returns the newest rows and passes the limit through', async () => {
  expect(await latestMessages(1)).toEqual(rows);
  expect(limit).toHaveBeenCalledWith(1);
});

A fake query chain like that only checks your logic. When I care about the SQL itself, I hit the real local D1 through the dev server. I'm fine with that trade.

Mocking your own modules

You don't have to mock at the void/* level. For void/live I mock my own stream module, because that's what my code imports:

// src/cards.ts
import { live } from './live';

export async function renameCard(id: string, title: string) {
  const clean = title.trim();
  if (!clean) throw new Error('Title is required');
  await live.publish(`card:${id}`, { title: clean }, { type: 'renamed' });
  return { id, title: clean };
}
// tests/cards.test.ts
import { beforeEach, expect, it, vi } from 'vite-plus/test';
import { renameCard } from '../src/cards';
import { live } from '../src/live';

vi.mock('../src/live', () => ({
  live: { publish: vi.fn(async () => {}) },
}));

beforeEach(() => vi.mocked(live.publish).mockClear());

it('publishes the trimmed title to the card topic', async () => {
  await renameCard('42', '  Ship it  ');
  expect(live.publish).toHaveBeenCalledWith('card:42', { title: 'Ship it' }, { type: 'renamed' });
});

it('rejects an empty title without publishing', async () => {
  await expect(renameCard('42', '   ')).rejects.toThrow('Title is required');
  expect(live.publish).not.toHaveBeenCalled();
});

AI gets the same treatment. My summarize() helper wraps ai.run() and returns early on an empty list, and the test checks both paths:

// tests/summarize.test.ts
import { expect, it, vi } from 'vite-plus/test';
import { ai } from 'void/ai';
import { summarize } from '../src/summarize';

vi.mock('void/ai', () => ({
  ai: { run: vi.fn(async () => ({ response: 'Everyone wants dark mode.' })) },
}));

it('skips the model when there is nothing to summarize', async () => {
  expect(await summarize([])).toBe('No comments yet.');
  expect(ai.run).not.toHaveBeenCalled();
});

it('returns the model response', async () => {
  expect(await summarize(['dark mode?', '+1 dark mode'])).toBe('Everyone wants dark mode.');
  expect(ai.run).toHaveBeenCalledOnce();
});

One oddity: once a file imported void/ai, the test run printed [void] AI requires authentication. Run void account login, then restart the dev server. The tests still passed and nothing called Cloudflare. It's the Void plugin noticing the import while Vitest loads your Vite config. Note the command it suggests, too. The AI docs tell a direct Cloudflare project to use void cloudflare login; void account login is the Void platform command. My scratch app had no deploy target yet, which is probably why.

Email needs no mocks at all. The void/email/testing helpers from Chapter 10 capture sends and inbound deliveries. My suite ran 8 tests across 5 files in under half a second.

void prepare and the .void/ folder

Void generates types into .void/: routes.d.ts for typed routes and fetch, db.d.ts for your schema, a tsconfig.json that pulls them in, plus things like the dev inbox token. The dev server keeps them fresh. Outside dev, run:

void prepare

I deleted .void/routes.d.ts and ran it; the file came back with entries for /live, /api/counter/[name] and /rooms/[room]. A second run printed No generated files changed. The starter's package.json already has "postinstall": "void prepare". In CI, make sure it runs after install and before any typecheck, or tsc fails on missing route types.

Remote dev is a platform feature

Void can point your local code at deployed D1, KV and R2 ("remote": true in config, or VOID_REMOTE=1). Per the docs, that needs a Void platform: void connect <url> plus a linked, deployed project. I don't run a platform, so I haven't tried it, and on a direct Cloudflare setup the local Miniflare bindings are what you get. AI is the one binding that's always remote either way.

That covers building and checking things on your own machine. Chapter 12 is about getting the app off it.

Deploying and Operating

I'll be upfront about this one: I didn't deploy anything to write it. Everything below comes from the Void 1.12.2 docs and the CLI's own --help output, which I ran locally. Part 2 deploys a real app to my own Cloudflare account, and that's where these commands get tested. A few claims need a real deploy to confirm, and each one has a marked note so it gets checked before this guide ships.

Two places your app can go

void deploy builds the app, provisions the resources it inferred from your code, applies pending migrations, and publishes. The question is where.

Your own Cloudflare account. This is what this guide uses:

void connect --platform cloudflare
void deploy --platform cloudflare

connect signs you in through the browser and asks for an account. After that the target is saved and plain void deploy works. Sessions have their own commands, separate from Wrangler's:

void cloudflare login    # sign in or switch users
void cloudflare status   # identity, credential source, deployment account
void cloudflare logout

A Void platform your team runs. That's void connect platform.example.com and void deploy --platform void --project my-app. More at the end of the chapter.

The docs mention a hosted "Void Cloud" in a few operator command references, but I couldn't find any way to sign up for one. In practice the choice is your account or a platform you install.

What deploy does to your data

Deploy applies SQL migrations from db/migrations/. If your schema changed and there's no migration for it, deploy stops and tells you to run void db generate. I like that guardrail.

For D1 on your own account, deploy saves a restore point before migrating and prints a void db restore --bookmark <b> command. A restore discards every write after that point, so it's a last resort.

On the companion app's first deploy, this is what it printed before running the one migration:

● Saved a D1 restore point before applying 1 migration.
  To undo these migrations, restore this point (discards every later write):
    void db restore --platform cloudflare --bookmark=00000000-0000000a-00005134-95b32107919fd3f79d4d07cd74aa4706

Copy that line somewhere before you do anything else. D1 Time Travel keeps restore points for a limited window, so a bookmark from months ago may be gone. I didn't run the restore against the live app, because it throws away every write since the bookmark.

Flags from void deploy --help worth knowing:

  • --skip-migrations ships code without applying SQL. The app must work with the current schema.
  • --atomic publishes a Durable Object Worker without pre-traffic staging. The docs want it when you add, rename or remove a Durable Object class, and you can't roll back across that change.

Commit void.config.ts and void.lock.json. The lock file holds Durable Object migration history; never delete or reorder deployed steps.

Deploy never uploads your .env. Production secrets go through void secret put NAME or void secret sync <file>.

Deploying from GitHub Actions

Once a target is saved, Void writes the workflow:

void init --github

Add CLOUDFLARE_API_TOKEN as a repository secret. Per the Cloudflare integration docs, the token needs Workers → Admin for the first deploy (Void creates the Worker), Workers → Editor after that, and access to whatever the app uses, like D1 or KV. Add CLOUDFLARE_ACCOUNT_ID if the token can see more than one account.

If the workflow typechecks before deploying, run void prepare after installing dependencies. As Chapter 11 showed, the types in .void/ don't exist in a fresh checkout until something generates them.

Run void connect --platform cloudflare first. Without a saved target, void init --github stops with "No Void platform connected." With one, it wrote .github/workflows/void-deploy.yml for the companion app:

name: Deploy to Cloudflare
on:
  push:
    branches: [main]

concurrency:
  group: void-cloudflare-deploy-${{ github.repository }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
      - uses: actions/setup-node@v6
        with:
          node-version: lts/*
          check-latest: true
          cache: npm
      - run: npm ci
      - name: Deploy
        env:
          CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          DATABASE_URL: ${{ secrets.DATABASE_URL }}
          CLOUDFLARE_WORKERS_SUBDOMAIN: ${{ vars.CLOUDFLARE_WORKERS_SUBDOMAIN }}
          CF_ACCESS_CLIENT_ID: ${{ secrets.CF_ACCESS_CLIENT_ID }}
          CF_ACCESS_CLIENT_SECRET: ${{ secrets.CF_ACCESS_CLIENT_SECRET }}
        run: npx void deploy --platform cloudflare

(I trimmed the generated comments.) Only CLOUDFLARE_API_TOKEN is required for a D1 app. DATABASE_URL is for Postgres or MySQL, and the Access pair only matters if Cloudflare Access sits in front of the Worker. node-version: lts/* has to resolve to 24.22 or later, which current LTS does, but pin it if you want builds you can reproduce.

Operating a live app

void project status
void project logs --level error
void project logs --filter websocket
void project rollback [deployId]

status on a Cloudflare target lists Worker Versions, marks the active one, and shows the recorded migration count.

logs on Cloudflare is a live tail with no history. --level error selects error invocations and --filter becomes Cloudflare's live search, but --range can't reach back in time. A Void platform keeps retained logs. Errors you catch and only save to your database won't appear, so console.error() them too.

requests (traffic, including edge errors that never reach your Worker) and cancel (stop an in-flight deploy) are hosted-only. A direct Cloudflare deploy runs from your machine or CI, so there's nothing remote to cancel.

One catch from the real deploy: I deployed with void deploy --platform cloudflare, and afterwards void project status answered "Not logged in. Run void account login first." The flag doesn't save a target. Running void connect --platform cloudflare once fixed it:

id                                    status  migrations  deployed
f77717d0-1352-4442-930f-5a62ebd825be  live    1           1m ago
void-board — 1 version

And void project logs tailing while I sent three requests:

GET https://void-board.<subdomain>.workers.dev/ - ok @ 2026-12-01, 10:14:40 a.m.
GET https://void-board.<subdomain>.workers.dev/nope - ok @ 2026-12-01, 10:14:41 a.m.

Notice the /nope request: the app answered it with a 404 page, and the tail still calls the invocation ok, because the Worker didn't throw. Use --level error for thrown errors and 5xx responses, not for 404s.

Rollback leaves your database alone

On Cloudflare, void project rollback takes a Worker Version ID (or an unambiguous prefix) and activates it at 100%. If the target has fewer applied migrations than the current version, Void shows the difference before you confirm.

It does not reverse migrations. Drop a column, roll back to code that still reads it, and that code fails. So write migrations the previous app version can live with, and treat void db restore as its own deliberate step, with a plan for the writes it throws away.

CPU limits and Workers Free vs Paid

Per-request CPU time lives in void.config.ts:

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

export default defineConfig({
  worker: {
    limits: { cpu_ms: 30000 },
  },
});

The value runs from 1 to 300000 ms, and on a direct deploy Cloudflare enforces its plan ceiling: Workers Free allows up to 10 ms, Workers Paid up to 300000 ms. Network waits don't count as CPU; parsing big payloads and rendering lots of HTML do.

Native Void apps run on Workers Free within its quotas. You need Paid for more than 10 ms of CPU, for email to arbitrary recipients (Chapter 10), or for Sandboxes.

The self-hosted platform, briefly

A Void platform lets a team deploy into a shared Cloudflare account without handing out account credentials, with retained logs and deploy history. It needs:

  • a Cloudflare account with Workers for Platforms (its own paid plan), R2 and Analytics Engine enabled
  • an empty hosted PostgreSQL database for the platform (Void creates the tables and a Hyperdrive connection; you provide the server)
  • a login provider: GitHub, Google, OIDC or Cloudflare Access
  • a domain for apps, or workers.dev for testing

void platform install --plan previews every resource without changing anything. For one person shipping their own apps, I don't think it's worth it; your own account has far fewer moving parts. For a team that wants a shared deploy target with guardrails, it starts to make sense. Chapter 23 comes back to that call.

That's Part 1. You've seen every piece on its own. Part 2 puts them together into one real app, starting with Chapter 13, "What We're Building."

What We're Building

Part 1 took Void apart one piece at a time. Routes in one scratch app, D1 in another, auth and realtime in a third. That's a fine way to learn an API and a poor way to find out how the pieces behave together.

So Part 2 builds one real app from an empty folder to a Cloudflare deploy. It's called Void Board, and every line of code in these chapters comes from its repo.

The app

Void Board is a small team board. Think of a stripped-down Trello for a handful of people:

  • Boards with members. You create a board and add teammates by email. Only members can see a board.
  • Cards in three columns. Todo, doing, done. Create, edit, move between columns, reorder, delete.
  • Comments on each card.
  • Attachments. Files go to R2, and a queue checks each one and writes a short preview.
  • Live updates. Everyone looking at a board sees a teammate's card change without reloading.
  • A nightly digest email, sent by a cron job.
  • An AI summary of a card's comments, streamed into the page as it's written.

That list touches almost every chapter of Part 1: routing, rendering, D1, R2, auth, queues, crons, SSE, Durable State, AI and email. Each one shows up here doing a real job.

How it fits together

The browser never runs a UI framework. Every page is HTML rendered on the server with Hono JSX (chapter 4). Interactivity comes from Datastar, a small script that reads data-* attributes, sends requests to the server, and patches the HTML that comes back into the page.

browser (HTML + Datastar 1.0.5)
   |  @get / @post             ^  text/event-stream:
   v                           |  datastar-patch-elements / -signals
Void routes (Hono JSX) --------+
   |-- D1 via Drizzle      boards, cards, comments, auth tables
   |-- R2                  attachment files
   |-- queue               attachment checks
   |-- Durable State       live board feed, AI quota
   '-- cron                nightly digest

A button click is a POST. The route does its work and answers with Server-Sent Events that say "replace #cards-todo with this HTML" or "set this signal to 3". Chapter 14 covers that protocol and the one Void gotcha that breaks it.

Why a native Void app

Void can run inside Astro or another framework (Part 3 covers that), but this app is a native Void app on purpose. Two things it needs are native-only.

Void-managed auth is the first. Chapter 7 showed that framework mode sends you to Better Auth directly. The second is custom Durable State modules, which chapter 9 flagged as native-only too, and the live board in chapter 18 runs on one.

The app is also API-only. There's no pages/ folder and no React, Vue, Svelte or Solid. Every route returns c.html(...) or a stream.

That has one setup cost. void init won't scaffold an API-only app from a script. With CI=1 it stopped with Pass --framework (react, vue, svelte, solid) when running without an interactive terminal, and there's no --framework none. I wrote the files by hand. It's five of them.

The skeleton

Unlike Part 1, this app uses plain Vite 8 rather than Vite+. The JSX setting from chapter 4 works with Vite's own defineConfig:

// vite.config.ts
import { defineConfig } from 'vite';
import { voidPlugin } from 'void';

export default defineConfig({
  // Route files are .tsx; compile their JSX with Hono's runtime, not React's.
  oxc: { jsx: { runtime: 'automatic', importSource: 'hono/jsx' } },
  plugins: [voidPlugin()],
});

Versions are pinned exactly. Void moves fast, and I'd rather upgrade on purpose:

{
  "dependencies": { "hono": "4.13.19" },
  "devDependencies": {
    "typescript": "7.0.2",
    "vite": "8.4.0",
    "vitest": "5.1.2",
    "void": "1.12.2"
  }
}

Hono gets pinned to the exact version Void 1.12.2 depends on (>=4.13.19 <4.13.20). The React starter from void init adds "hono": "^4.11.9", and a caret range can drift ahead of Void's copy. Then you have two Hono instances, two HTTPException classes, and instanceof checks that quietly fail.

The layout is chapter 4's pattern with one addition, the Datastar script:

// src/views/layout.tsx (trimmed)
export const DATASTAR_SRC = '/vendor/datastar-1.0.5.js';

export function Layout({ title, children }: LayoutProps) {
  return (
    <>
      {raw('<!doctype html>')}
      <html lang="en">
        <head>
          <title>{`${title} · Void Board`}</title>
          <link rel="stylesheet" href="/app.css" />
          <script type="module" src={DATASTAR_SRC}></script>
        </head>
        <body>
          <header class="site-header">
            <a class="brand" href="/">Void Board</a>
            <nav id="nav"></nav>
          </header>
          <main>{children}</main>
        </body>
      </html>
    </>
  );
}

Why Datastar is vendored

I planned to load Datastar from a CDN. Then I looked at npm. The @starfederation/datastar package stops at 1.0.0-beta.11. The stable 1.0 releases only exist as GitHub releases, which jsDelivr serves through its gh/ path.

So I downloaded 1.0.5 once and committed it:

curl -sSfL -o public/vendor/datastar-1.0.5.js \
  https://cdn.jsdelivr.net/gh/starfederation/datastar@v1.0.5/bundles/datastar.js

Files in public/ are served as-is, and the app has no runtime dependency on a CDN.

Repo layout

Here's where everything lands by the end of Part 2:

routes/            HTTP routes (file-based; Hono under the hood)
middleware/        global middleware (route protection)
durable-objects/   board feed (live updates), summary quota
queues/            attachment processing
crons/             nightly digest
db/                Drizzle schema, migrations, seed
src/lib/           Datastar helpers, data access, live feed client, AI providers
src/views/         Hono JSX components
tests/             Vitest
public/            static files, including the vendored Datastar 1.0.5 bundle
auth.ts, env.ts    Better Auth config, environment schema

src/ has no special meaning to Void, so that's where everything that isn't a route, job or object lives.

Following along

The repo is at github.com/freekrai/void-board. Each chapter maps to a git tag: ch13 is this skeleton, ch14 adds the Datastar helper, and so on up to ch21. Chapter 18 has an extra ch18-spikes tag with both live-update designs side by side.

git clone https://github.com/freekrai/void-board
cd void-board
git checkout ch13      # or any later tag
npm install
npm run dev            # http://localhost:5173

From ch15 on, npm run db:seed loads two users and a board. Sign in as ada@example.com or grace@example.com with the password correct-horse-battery.

Four things to know before you run it.

Node. You need ^24.22.0 || >=26.12.0, and .nvmrc pins 24.22.3. Check node --version itself. On my machine nvm use 24.22.3 printed "Now using node v24.22.3" while node --version still said v26.13.1, because a mise shim sat earlier on PATH.

npm 11. npm 11.20 blocks dependency install scripts by default, and Void needs two of them (esbuild and workerd). The repo's package.json approves them with an allowScripts block:

"allowScripts": {
  "better-sqlite3": false,
  "esbuild": true,
  "workerd": true,
  "fsevents": false
}

npm install-scripts approve writes version-pinned keys like "esbuild@0.28.2": true. I switched them to bare names so an upgrade doesn't silently block them again. better-sqlite3 ships prebuilt binaries, so its build script can stay off.

void prepare runs twice. On a fresh clone, one void prepare generates the auth schema but leaves its path mapping out of .void/tsconfig.json, and tsc fails with Cannot find module '@auth-schema'. A second run fixes it. From ch21 the postinstall script runs it twice. On ch15 through ch20, run npx void prepare once more before tsc, or use npm run typecheck, which does it for you. vite dev and vite build work either way.

No Cloudflare account needed. Dev, tests and builds all run locally in Miniflare.

A deployed copy

When the app was done, I deployed it to my own Cloudflare account with npx void deploy --platform cloudflare. A deployed copy runs at void-board.datamcfly.workers.dev. Sign-up, sign-in and creating a board all worked there. The seed users only exist in local databases, so make your own account.

Next, chapter 14 wires Datastar into Void and fixes the newline bug that turns a multi-line patch into an empty div.

Datastar on Void

Datastar turns data-* attributes into behaviour, sends requests to your server, and patches whatever the server streams back into the page. The server stays in charge of the HTML. That fits Void's routes well.

It needs one fix first. Send multi-line HTML through void/sse and Datastar patches an empty div, with no error anywhere. The cause sits between void/sse and Datastar's parser. This chapter covers the Datastar you need for the board, that bug, and the small helper I wrote around it. Code is at tag ch14.

The Datastar you need

Four ideas carry the whole app.

Signals are reactive values declared in the HTML. data-signals="{name: '', greetings: 0}" creates $name and $greetings. data-bind="name" ties an input to $name, and data-text="$greetings" keeps an element's text in sync.

data-on runs an expression on an event: data-on:click="@post('/demo/greet')".

Actions like @get and @post send a request with a Datastar-Request: true header. Signals travel along: as ?datastar=<json> on GET and DELETE, and as a JSON body on POST, PUT and PATCH.

Patch events are what the server sends back, as text/event-stream. datastar-patch-elements carries HTML. Datastar finds the element with the same id and morphs it. datastar-patch-signals carries JSON that updates signals.

Here's the demo page from the repo:

// routes/demo/index.tsx (trimmed)
export const GET = defineHandler((c) =>
  c.html(
    <Layout title="Datastar demo">
      <div data-signals="{name: '', greetings: 0, ticks: 0}">
        <input id="name" data-bind="name" placeholder="Ada" />
        <button class="primary" data-on:click="@post('/demo/greet')">Greet me</button>
        greetings sent: <strong data-text="$greetings"></strong>
        <div id="greeting"></div>

        <button data-on:click="@get('/demo/stream')">Stream five ticks</button>
        ticks: <strong data-text="$ticks"></strong>
        <ul id="ticks" class="list"></ul>
      </div>
    </Layout>,
  ),
);

Notice data-bind="name". Plain-HTML Datastar examples write data-bind:name with no value. In Hono JSX that renders as data-bind:name="true", because JSX turns a valueless attribute into a boolean. Datastar then throws KeyAndValueProvided (rawKey: "bind:name", key: "name", value: "true"). Use the value form for any Datastar attribute you'd normally write bare.

The empty div

Chapter 9 showed that void/sse splits a multi-line data string into one data: line per line. That's correct SSE. Datastar reads those lines differently than EventSource would. It joins them with \n, then splits each line at its first space into a key and a value. The key on every line has to say what the line is.

So this looks right, and it breaks:

// routes/demo/naive.dev.ts
export const GET = defineHandler(() =>
  eventStream(async (stream) => {
    await stream.send({
      event: 'datastar-patch-elements',
      data: 'elements <div id="greeting">\n<p>second line</p>\n</div>',
    });
  }),
);

On the wire, only the first line carries the elements key:

event: datastar-patch-elements
data: elements <div id="greeting">
data: <p>second line</p>
data: </div>

Datastar reads <p>second and </div> as two bogus keys and drops them. In the browser, #greeting became an empty div. innerHTML was "", and the console had nothing in it.

Hono JSX hides this for a while, because its output comes out on one line. The first time you use the html template tag or pretty-printed markup, you hit it. Void's SSE docs don't mention the splitting, so I kept that broken route as a .dev.ts file to show it.

The helper

The fix is to put the key on every line before handing the data to Void:

// src/lib/datastar.ts (trimmed)
import { formatSseText, type SseTextMessage } from 'void/sse';

const NEWLINE = /\r\n|\r|\n/;

function prefixLines(key: string, value: string): string[] {
  return value.split(NEWLINE).map((line) => `${key} ${line}`);
}

function message(event: string, lines: string[], opts: EventOptions): SseTextMessage {
  return { event, id: opts.id, retry: opts.retry, data: lines.join('\n') };
}

export function patchElements(html: string, opts: PatchElementsOptions = {}): SseTextMessage {
  const lines: string[] = [];
  if (opts.selector) lines.push(`selector ${opts.selector}`);
  if (opts.mode && opts.mode !== 'outer') lines.push(`mode ${opts.mode}`);
  if (opts.useViewTransition) lines.push('useViewTransition true');
  if (html !== '') lines.push(...prefixLines('elements', html));
  return message('datastar-patch-elements', lines, opts);
}

export function patchSignals(
  signals: Record<string, unknown>,
  opts: PatchSignalsOptions = {},
): SseTextMessage {
  const lines: string[] = [];
  if (opts.onlyIfMissing) lines.push('onlyIfMissing true');
  lines.push(...prefixLines('signals', JSON.stringify(signals)));
  return message('datastar-patch-signals', lines, opts);
}

/** Serialize events into one SSE body, for handlers that answer in one go. */
export function formatEvents(events: SseTextMessage[]): string {
  return events.map((event) => formatSseText(event)).join('');
}

/** A complete text/event-stream Response for a short-lived @get/@post. */
export function datastarResponse(...events: SseTextMessage[]): Response {
  return new Response(formatEvents(events), {
    headers: {
      'Content-Type': 'text/event-stream; charset=utf-8',
      'Cache-Control': 'no-cache, no-transform',
    },
  });
}

Every function returns a plain { event, data, id, retry } object. That's the shape stream.send() takes, so a long stream and a one-shot response use the same messages. The file also has removeElements, readSignals (which reads ?datastar= or the JSON body, depending on the method) and isDatastarRequest.

A POST that answers once uses datastarResponse:

// routes/demo/greet.ts
export const POST = defineHandler(async (c) => {
  const signals = await readSignals<DemoSignals>(c.req.raw);
  const name = (signals.name ?? '').trim() || 'stranger';
  const greetings = (signals.greetings ?? 0) + 1;

  const fragment = await html`<div id="greeting">
  <p>Hello, <strong>${name}</strong>!</p>
  <p class="muted">Rendered on the server at ${new Date().toISOString()}</p>
</div>`;

  return datastarResponse(patchElements(String(fragment)), patchSignals({ greetings }));
});

hono/html's html tag returns a promise (or a string), so await it and String() it first. I posted a name with a script tag in it:

event: datastar-patch-elements
data: elements <div id="greeting">
data: elements   <p>Hello, <strong>&lt;script&gt;Ada&lt;/script&gt;</strong>!</p>
data: elements   <p class="muted">Rendered on the server at 2026-12-01T16:33:32.276Z</p>
data: elements </div>

event: datastar-patch-signals
data: signals {"greetings":3}

Every line keyed, the name escaped. A long-lived stream uses the same helpers inside eventStream:

// routes/demo/stream.ts (loop body)
await stream.send(patchElements(String(item), { selector: '#ticks', mode: 'append' }));
await stream.send(patchSignals({ ticks: tick }));

That came back chunked, with five append patches about 300 ms apart. In headless Chromium with Datastar 1.0.5, typing Ada <b> and clicking the button rendered Hello, Ada &lt;b&gt;, $greetings went to 1, and the stream added five <li>s.

The repo has 13 Vitest tests for this file at this tag. They include a tiny parser that mimics Datastar's, so the test for the bug reads like the bug:

it('shows why the prefix matters: an unprefixed frame loses lines', () => {
  const html = '<ul id="list">\n<li>one</li>\n</ul>';
  const naive = formatSseText({ event: 'datastar-patch-elements', data: `elements ${html}` });
  expect(parseFrame(naive).fields.elements).toBe('<ul id="list">');
});

Why not the official SDK?

I read @starfederation/datastar-sdk@1.0.0 before writing my own. The SDK prefixes every line, so it doesn't have this bug, and it's a fine choice if you'd rather not own protocol code. I went with the helper for four reasons:

  • Its messages drop into Void's stream.send(), so I keep everything void/sse already does: 15-second keep-alive comments, stream.closed, abort on the request signal, and SseStreamClosedError after a disconnect. The SDK's stream() builds its own ReadableStream without keep-alive pings.
  • The same message objects can be written into any stream. Chapter 18 needs that, because live events come from a Durable Object rather than from the handler that opened the stream.
  • The SDK's package root resolves to its Node build. On Workers you have to import @starfederation/datastar-sdk/web. Easy to get wrong.
  • The whole file is 100 lines with comments, small enough to test exhaustively and quote in a guide.

Two rules that shape every route

Datastar 1.0.5 has two behaviours you'll design around for the rest of Part 2. I found both in its bundle while building chapter 16, and the first one is why my first middleware's redirect never ran.

First, Datastar ignores the body of any response that isn't a 200. A 400 with validation errors, a 401, a 404: nothing gets patched. So a route that wants the page to show an error has to answer 200 with a patch.

Second, redirects get followed. A 302 in reply to @post is followed by fetch, and the HTML of the page you redirected to comes back and gets patched into the current page. To send someone elsewhere, you answer 200 with a patch that navigates. Chapter 16 adds a redirect() helper for exactly that.

Datastar will also accept a plain text/html or application/json response, and a 204 does nothing. I use SSE everywhere so every route speaks one format.

Chapter 15 builds the database: the schema, the first migration, and seed users you can actually sign in as.

Schema and Seed Data

The board needs five tables of its own and four from Better Auth. This chapter writes the Drizzle schema, generates one migration that holds all nine, and seeds two users you can actually sign in as. That last part was harder than it sounds. Code is at tag ch15.

Chapter 5 covered the commands: void db generate, migrate, status and seed. I'll stick to what was new when the app got real.

Turn auth on first

My cards have a created_by column, and a board has an owner. Both should be foreign keys to Better Auth's user table. That table's Drizzle definition lives in @auth-schema, a generated module. And before auth was enabled, it didn't exist. .void/tsconfig.json had no @auth-schema path at all, so db/schema.ts had nothing to point at.

The fix is to turn auth on now, one chapter before sign-in. Chapter 7 listed the triggers. I used a root auth.ts that changes nothing yet:

// auth.ts
import { defineAuth } from 'void/auth';

// Email + password is on by default. Spread `defaults` to keep Void's wiring.
export default defineAuth(({ defaults }) => ({
  ...defaults,
}));

Then npx void prepare generated .void/better-auth-schema.ts, and userTable became importable. On a fresh clone you need void prepare twice before tsc passes (chapter 13 has the details).

The schema

Two small helpers keep the table definitions short. IDs are random UUIDs as text, which matches Better Auth's text user IDs. Timestamps are milliseconds, with a SQL default so rows inserted outside Drizzle still get one:

// db/schema.ts
import { userTable } from '@auth-schema';
import { sql } from 'void/db';
import { index, integer, primaryKey, real, sqliteTable, text } from 'void/schema-d1';

const id = () =>
  text('id')
    .primaryKey()
    .$defaultFn(() => crypto.randomUUID());

const createdAt = () =>
  integer('created_at', { mode: 'timestamp_ms' })
    .notNull()
    .default(sql`(unixepoch('subsec') * 1000)`);

export const COLUMNS = ['todo', 'doing', 'done'] as const;
export type Column = (typeof COLUMNS)[number];

Boards have an owner, and membership is its own table with a composite primary key:

export const boards = sqliteTable('boards', {
  id: id(),
  name: text('name').notNull(),
  ownerId: text('owner_id')
    .notNull()
    .references(() => userTable.id, { onDelete: 'cascade' }),
  createdAt: createdAt(),
});

export const boardMembers = sqliteTable(
  'board_members',
  {
    boardId: text('board_id')
      .notNull()
      .references(() => boards.id, { onDelete: 'cascade' }),
    userId: text('user_id')
      .notNull()
      .references(() => userTable.id, { onDelete: 'cascade' }),
    role: text('role', { enum: ['owner', 'member'] })
      .notNull()
      .default('member'),
  },
  (t) => [primaryKey({ columns: [t.boardId, t.userId] }), index('board_members_user_idx').on(t.userId)],
);

The primary key answers "is this user a member of this board?", which every board route in chapter 17 asks. The extra index on user_id serves the other direction: the list of boards a user belongs to.

Cards are the interesting table:

export const cards = sqliteTable(
  'cards',
  {
    id: id(),
    boardId: text('board_id')
      .notNull()
      .references(() => boards.id, { onDelete: 'cascade' }),
    column: text('column', { enum: COLUMNS }).notNull().default('todo'),
    // Fractional ordering: a card dropped between two others takes the midpoint.
    position: real('position').notNull(),
    title: text('title').notNull(),
    description: text('description').notNull().default(''),
    createdBy: text('created_by').references(() => userTable.id, { onDelete: 'set null' }),
    createdAt: createdAt(),
    updatedAt: integer('updated_at', { mode: 'timestamp_ms' })
      .notNull()
      .default(sql`(unixepoch('subsec') * 1000)`)
      .$onUpdate(() => new Date()),
  },
  (t) => [index('cards_board_column_idx').on(t.boardId, t.column, t.position)],
);

position is a REAL. With integer positions, putting a card between 1 and 2 means renumbering everything after it. With floats, the card between 1000 and 2000 takes 1500 and nothing else moves. The seed spaces cards 1000 apart, and new cards go to the bottom at max(position) + 1000. One caveat: chapter 17's moves only swap neighbours or append to a column, so nothing uses a midpoint yet. The column type leaves room for drag and drop later without a migration.

The index covers the one query the board page runs most: cards for a board, by column, in order.

The foreign keys make two different choices. Delete a user and their boards and memberships go with them (cascade). Cards and comments they wrote stay, with the author set to null, because a teammate's card shouldn't vanish when they leave.

comments is a card ID, an author and a body. attachments gets a storage_key (the R2 key, unique), the original filename, type and size, plus a status of pending, ready or failed and a preview. Chapter 19 fills those in from a queue. I put the table in now so the first migration has the whole model.

The migration

npx void db generate

That wrote db/migrations/20261201163507_magenta_catseye.sql with nine tables: my five plus account, session, user and verification. As chapter 7 found, void db generate puts the auth tables in your app's migration once auth is on. There's no separate Better Auth CLI step.

The cards table came out the way I wanted:

CREATE TABLE `cards` (
	`id` text PRIMARY KEY NOT NULL,
	`board_id` text NOT NULL,
	`column` text DEFAULT 'todo' NOT NULL,
	`position` real NOT NULL,
	`title` text NOT NULL,
	`description` text DEFAULT '' NOT NULL,
	`created_by` text,
	`created_at` integer DEFAULT (unixepoch('subsec') * 1000) NOT NULL,
	`updated_at` integer DEFAULT (unixepoch('subsec') * 1000) NOT NULL,
	FOREIGN KEY (`board_id`) REFERENCES `boards`(`id`) ON UPDATE no action ON DELETE cascade,
	FOREIGN KEY (`created_by`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE set null
);

One thing looked wrong. The file creates attachments, which references user, before it creates user. SQLite accepts forward foreign key references, and the migration applied cleanly. I left it alone.

Seed users you can sign in as

A board app with no users is useless to click around in. I wanted npm run db:seed to give me two people who can sign in with a password. That's where it got awkward.

defineSeed's schema argument only covers db/schema.ts. The auth tables aren't in it. Importing them from @auth-schema and inserting directly works fine. The password is the problem. Better Auth stores a hash in the account table, and Void replaces Better Auth's hasher with its own.

I read it in node_modules/void/dist/ (voidAuthPassword): Node's scrypt with N=16384, r=16, p=1, a 64-byte key, the password NFKC-normalized, and a 16-byte random salt as hex, used as a string. It's stored as salt:key. So the seed reproduces it:

// db/seed.ts (hash)
import { randomBytes, scrypt } from 'node:crypto';

// Matches the password format Void's auth uses (void 1.12.2):
// scrypt N=16384 r=16 p=1, 64-byte key, stored as "<salt hex>:<key hex>".
// It's an internal detail, so the sign-in test in ch16 guards it.
function hashPassword(password: string): Promise<string> {
  const salt = randomBytes(16).toString('hex');
  return new Promise((resolve, reject) => {
    scrypt(
      password.normalize('NFKC'),
      salt,
      64,
      { N: 16384, r: 16, p: 1, maxmem: 64 * 1024 * 1024 },
      (error, key) => (error ? reject(error) : resolve(`${salt}:${key.toString('hex')}`)),
    );
  });
}

This is undocumented and internal. A Void upgrade could change the format, and seeded users would stop being able to sign in. Chapter 16's sign-in against a seeded user is the tripwire. The alternative is to POST to /api/auth/sign-up/email once the dev server is running, which can't live inside defineSeed.

The seed then inserts a user row and a credential account per person:

// db/seed.ts (users)
export default defineSeed<typeof import('./schema')>(async ({ db, schema }) => {
  const now = new Date();
  const people = [
    { id: crypto.randomUUID(), name: 'Ada', email: 'ada@example.com' },
    { id: crypto.randomUUID(), name: 'Grace', email: 'grace@example.com' },
  ];

  await db.insert(userTable).values(
    people.map((p) => ({ ...p, emailVerified: true, createdAt: now, updatedAt: now })),
  );
  await db.insert(accountTable).values(
    await Promise.all(
      people.map(async (p) => ({
        id: crypto.randomUUID(),
        accountId: p.id,
        providerId: 'credential',
        userId: p.id,
        password: await hashPassword(SEED_PASSWORD),
        createdAt: now,
        updatedAt: now,
      })),
    ),
  );
  // ...then one board with both as members, four cards, three comments
});

The rest is plain inserts through schema: a "Launch plan" board owned by Ada, Grace as a member, four cards across the three columns, and three comments on the first card.

npm run db:seed        # void db seed --yes
# Reset database. Applied 1 migration.
# Seeded from db/seed.ts.

To check it, I ran several statements in one go. void db execute prints nothing for multi-statement SQL by design. Add --json to see every statement's rows. Both accounts had providerId: 'credential' and 161-character hashes (32 hex characters of salt, a colon, 128 of key). created_at values were milliseconds, like 1796142924816.

The seed resets the database, then prints Restart your dev server if it's running. Take that literally. My dev server kept serving its old connection until I restarted it.

A limit to remember

D1 allows at most 100 bound parameters in one statement. Nothing in this chapter gets close. Chapter 19's digest cron did, with an inArray() over every card ID on a board that had grown past 100 cards, and failed with too many SQL variables. Every value in a multi-row insert is a bound parameter too, so I'd guess a much bigger seed would hit the same wall. I didn't test that.

Chapter 16 puts these users to work: sign-up and sign-in forms submitted through Datastar, with errors patched into the page.

Sign-In

Chapter 7 drove Better Auth with curl against /api/auth. A real app needs forms: a sign-up page, a sign-in page, errors that show up under the right field, and board routes that bounce signed-out visitors. This chapter builds those with server-rendered forms and Datastar, and runs into both Datastar rules from chapter 14 head first. Code is at tag ch16.

The forms

Both pages render one shared component. Each field gets an empty <p id="error-..."> under it, and the form gets one more for errors that don't belong to a single field:

// src/views/auth.tsx
export function FieldError({ name, errors }: { name: string; errors?: FieldErrors }) {
  return (
    <p id={`error-${name}`} class="error">
      {errors?.[name] ?? ''}
    </p>
  );
}

export function AuthForm(props: { action: string; submit: string; fields: Field[] }) {
  return (
    <form
      class="stack"
      data-on:submit={`@post('${props.action}', {contentType: 'form'})`}
      data-indicator="submitting"
    >
      {props.fields.map((f) => (
        <>
          <label for={f.name}>{f.label}</label>
          <input id={f.name} name={f.name} type={f.type} autocomplete={f.autocomplete} required />
          <FieldError name={f.name} />
        </>
      ))}
      <FieldError name="form" />
      <button class="primary" type="submit" data-attr:disabled="$submitting">
        {props.submit}
      </button>
    </form>
  );
}

{contentType: 'form'} makes Datastar send the form's FormData instead of signals, so the handler reads ordinary form fields. data-on:submit on a form also stops the native submit. In the browser, the URL didn't change after a failed sign-in. data-indicator sets $submitting while the request is out, and the button disables itself.

The page source shows @post(&#39;/auth/sign-in&#39;, ...). Hono escapes quotes in attributes, and browsers unescape them, so Datastar sees the right expression.

GET /sign-in and GET /sign-up wrap that in the layout and send signed-in visitors to /boards.

The handler

Here's the whole sign-in route:

// routes/auth/sign-in.ts
const FIELDS = ['email', 'password'];

export const POST = defineHandler(async (c) => {
  const input = validate(SignInSchema, formFields(await c.req.parseBody(), FIELDS));
  if (!input.ok) return datastarResponse(...errorPatches(FIELDS, input.errors));

  try {
    // Void forwards the session cookie this call sets onto our response.
    await getAuth(c).api.signInEmail({ body: input.value, headers: c.req.raw.headers });
  } catch (error) {
    if (!authErrorCode(error)) throw error;
    return datastarResponse(...errorPatches(FIELDS, { form: 'Wrong email or password.' }));
  }
  return datastarResponse(redirect('/boards'));
});

Chapter 3 used defineHandler.withValidator() for this kind of thing, and it does parse form bodies. But when validation fails, it answers 400 {"error":"Validation failed",...}. Datastar ignores the body of any non-200 response, so the user would see nothing. I call valibot myself and keep the first message per field:

// src/lib/validate.ts (trimmed)
export function validate<S extends v.GenericSchema>(
  schema: S,
  input: unknown,
): Validated<v.InferOutput<S>> {
  const result = v.safeParse(schema, input);
  if (result.success) return { ok: true, value: result.output };
  const errors: FieldErrors = {};
  for (const issue of result.issues) {
    const key = v.getDotPath(issue) ?? 'form';
    errors[key] ??= issue.message;
  }
  return { ok: false, errors };
}

The email schema trims and lower-cases before it checks the format, so ADA@example.com signs in as Ada. The sign-up schema wants at least 8 characters of password, the same as Better Auth's default minimum, so people see my message instead of Better Auth's.

Errors as patches

errorPatches sends one patch for every error paragraph on the form, including the ones with no error:

// src/lib/auth-errors.ts
export function errorPatches(fields: string[], errors: FieldErrors) {
  return [...fields, 'form'].map((name) =>
    patchElements(`<p id="error-${name}" class="error">${escapeHtml(errors[name] ?? '')}</p>`),
  );
}

The blanks matter. They clear whatever error the last attempt left behind.

Better Auth throws an APIError with a code. I didn't want to import better-auth directly, since it isn't one of my dependencies, and the import only works because npm hoists Void's copy. So authErrorCode() duck-types it by reading error.body.code. Anything that isn't an auth error gets rethrown.

Every sign-in failure maps to one message, "Wrong email or password.", so the form doesn't reveal which emails have accounts. Sign-up can't avoid that. Better Auth's USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL becomes "That email already has an account."

Redirecting from a Datastar request

Success needs to send the browser to /boards. A 302 won't work here, because fetch follows it and Datastar patches the boards page's HTML into the sign-in page. Datastar has no redirect event, either. So redirect() sends a script that navigates and then removes itself:

// src/lib/datastar.ts
export function redirect(url: string, opts: EventOptions = {}): SseTextMessage {
  // JSON.stringify quotes the URL; escaping "<" keeps "</script>" out of it.
  const target = JSON.stringify(url).replace(/</g, '\\u003c');
  return patchElements(
    `<script data-effect="el.remove()">window.location.href = ${target}</script>`,
    { ...opts, selector: 'body', mode: 'append' },
  );
}

The official Datastar SDK does the same trick for its executeScript. Two new tests cover the escaping.

Guarding the board routes

One global middleware protects /boards, /live and /attachments, plus everything under them:

// middleware/01.require-user.ts
const PROTECTED = ['/boards', '/live', '/attachments'];

export default defineMiddleware(async (c, next) => {
  const path = c.req.path;
  const isProtected = PROTECTED.some((p) => path === p || path.startsWith(`${p}/`));
  if (!isProtected || getUser()) return next();

  // Must stay 200: Datastar ignores the body of any other status.
  if (isDatastarRequest(c.req.raw)) return datastarResponse(redirect('/sign-in'));
  return c.redirect('/sign-in');
});

A browser navigation gets a normal 302 to /sign-in. A Datastar request, say an @post from a board whose session just expired, gets a 200 with the redirect script. My first version returned that script with a 401. It never ran.

The route itself still checks:

// routes/boards/index.tsx
export const GET = defineHandler((c) => {
  // Synchronous: Void resolved the session before this handler ran.
  const user = requireAuth(c, { throwRedirect: '/sign-in' });
  return c.html(
    <Layout title="Boards" user={user}>
      <h1>Your boards</h1>
      <p>Signed in as {user.email}.</p>
    </Layout>,
  );
});

Chapter 7 settled that requireAuth is synchronous in 1.12.2. Reading the source told me why. Void's auth middleware calls getSession() before your handler on every request whose path doesn't start with /__, and stores the user on the context. requireAuth(c) just reads c.get('user'), and getUser() reads the same value without the context.

Two consequences. Every request pays for a session lookup, public pages included. And the user is fixed at the start of the request: right after signInEmail, getUser() in the same handler still returns null. That's one more reason to redirect after sign-in instead of rendering the next page inline.

The Origin header

Here's the curl run, signing in as the seeded Ada with an upper-case email:

B=http://localhost:5173
curl -s -H 'datastar-request: true' -H "Origin: $B" \
  -F email=ADA@example.com -F password=correct-horse-battery \
  -c jar.txt $B/auth/sign-in
curl -s -b jar.txt $B/boards

The response set better-auth.session_token (Max-Age=604800, HttpOnly, SameSite=Lax) and cache-control: no-store, and /boards rendered. So chapter 15's hand-rolled password hash matches Void 1.12.2.

Then I sent the same request with Origin: https://evil.example.com. The handler ran, signInEmail succeeded, and my code sent its success redirect. But no cookie came back. Void logged Did not send cookies set by auth.api calls on a POST request from https://evil.example.com. Add this origin to auth trustedOrigins if it should change the session.

Cookies from auth.api calls only reach the response for trusted origins, and the default is the request's own origin. Same-origin requests and curl without an Origin header both got the cookie. In chapter 7, Better Auth's own endpoints refused a foreign origin with a 403. Here the request looks like it worked. Send the real Origin in scripts and tests.

What I checked

With curl: a wrong password patched Wrong email or password. into #error-form. Signing out cleared the session cookies, and /boards went back to 302. Signed out, a Datastar request to /boards got the 200 redirect patch.

In Chromium with Datastar 1.0.5: a short sign-up password showed the inline error without leaving the page, a valid sign-up landed on /boards signed in, Sign out returned home, and a wrong password stayed on /sign-in with the form error.

On the deployed copy from chapter 13, sign-up and sign-in worked, and a signed-out /boards returned 302.

Secrets outside dev

Dev uses a fixed built-in Better Auth secret, so it needs no setup. vite preview of the production build does. Without BETTER_AUTH_SECRET, every route returned 500, the home page included, with auth: Missing Better Auth secret. The auth middleware runs on every request.

Setting it as a shell variable didn't reach the Worker. Putting BETTER_AUTH_SECRET=<hex> in the root .env did. A real deploy creates the secret if it's missing, as chapter 7 covered. Production also gets Better Auth's per-IP sign-in rate limits, which dev turns off.

Next, chapter 17, "Cards CRUD with Datastar," uses the same patch-and-redirect pattern to create, edit, move and delete cards.

Cards CRUD with Datastar

This is the chapter where the board starts to feel like an app. You can create a board, add cards to three columns, edit them, move them left, right, up and down, and delete them. Every one of those actions is a Datastar request that gets HTML patches back.

The code is at the ch17 tag of the companion repo. It builds on the patchElements() helper from Chapter 14 and the forms and route guard from Chapter 16.

The routes

Here's the whole surface. File routes, so each row is a file under routes/boards/:

Method

Path

Does

GET/POST

/boards

list boards, create one

GET

/boards/:boardId

the board page: 3 columns, a card panel, an add-member form

POST

/boards/:boardId/members

add an existing user by email

POST

/boards/:boardId/cards

create a card

GET

/boards/:boardId/cards/:cardId

open the card panel with comments

POST

/boards/:boardId/cards/:cardId

save an edit

DELETE

/boards/:boardId/cards/:cardId

delete

GET

/boards/:boardId/cards/:cardId/edit

swap the card for its edit form

POST

/boards/:boardId/cards/:cardId/move

?to=doing or ?dir=up

POST

/boards/:boardId/cards/:cardId/comments

add a comment

Only the two GET pages return a full HTML document. Everything else answers with a text/event-stream body of patches.

One guard for every board route

Every board route starts with the same line. requireBoard() signs the user in (or redirects) and checks membership:

// src/lib/guard.ts
import { HTTPException } from 'hono/http-exception';
import type { CloudContext } from 'void';
import { requireAuth } from 'void/auth';
import { getBoardForUser } from './boards';

/** Signed-in user + a board they belong to, or 404 (don't reveal other boards). */
export async function requireBoard(c: CloudContext) {
  const user = requireAuth(c, { throwRedirect: '/sign-in' });
  const board = await getBoardForUser(c.req.param('boardId') ?? '', user.id);
  if (!board) throw new HTTPException(404, { message: 'Board not found' });
  return { user, board };
}

A non-member gets a 404, because a 403 would confirm the board exists. I tested it with curl as Mallory, a third account that isn't on the board: GET the board, POST an edit, DELETE a card, all 404. Ada using a real card ID under the wrong board ID also got a 404, because getCard() matches on both IDs.

requireAuth is synchronous here. Chapter 16 covered why: Void resolves the session before your handler runs.

Creating a card

The new-card form posts as a form, the same pattern Chapter 16 used for sign-in:

// src/views/board.tsx (trimmed)
export function NewCardForm({ boardId, column, error }: { boardId: string; column: Column; error?: string }) {
  return (
    <form id={`new-card-${column}`} data-on:submit={`@post('/boards/${boardId}/cards', {contentType: 'form'})`}>
      <input type="hidden" name="column" value={column} />
      <input name="title" placeholder="Add a card" aria-label={`New card in ${COLUMN_LABELS[column]}`} maxlength={200} />
      <p class="error">{error ?? ''}</p>
    </form>
  );
}

And the handler:

// routes/boards/[boardId]/cards/index.tsx
export const POST = defineHandler(async (c) => {
  const { user, board } = await requireBoard(c);
  const fields = formFields(await c.req.parseBody(), ['column', 'title']);
  const input = validate(NewCardSchema, fields);
  const column = isColumn(fields.column) ? fields.column : 'todo';
  if (!input.ok) {
    const error = input.errors.title ?? input.errors.column;
    const form = await render(<NewCardForm boardId={board.id} column={column} error={error} />);
    return datastarResponse(patchElements(form));
  }

  await createCard(board.id, user.id, input.value.column, input.value.title);
  // A fresh form, swapped in with mode "replace" so the typed text is cleared.
  const form = await render(<NewCardForm boardId={board.id} column={column} />);
  return datastarResponse(
    ...(await columnPatches(board.id, [input.value.column])),
    patchElements(form, { mode: 'replace' }),
  );
});

render() is a one-liner, String(await jsx), because Hono JSX can return a promise.

Validation errors are patches too

The schemas are valibot. The card one:

// src/lib/schemas.ts
export const NewCardSchema = v.object({
  column: v.picklist(['todo', 'doing', 'done'], 'Unknown column.'),
  title: v.pipe(v.string(), v.trim(), v.nonEmpty('A card needs a title.'), v.maxLength(200, 'Keep titles under 200 characters.')),
});

validate() wraps v.safeParse and keeps the first message per field. On failure the handler re-renders the form with the error in it and patches that. In the browser, submitting a blank title showed "A card needs a title." under the input, and nothing was written.

I don't use defineHandler.withValidator() for forms. Its failure is a 400 with a JSON body, and Datastar ignores anything that isn't a 200 (Chapter 16 again). I do use it for the move route, where the buttons build the URL and a bad query means a bug or someone poking at it:

// routes/boards/[boardId]/cards/[cardId]/move.ts
export const POST = defineHandler.withValidator({ query: MoveQuerySchema })(async (c, { query }) => {
  const { board } = await requireBoard(c);
  const moved = await moveCard(board.id, c.req.param('cardId') ?? '', query);
  if (!moved) return c.notFound();
  return datastarResponse(...(await columnPatches(board.id, moved.columns)));
});

One wart: MoveQuerySchema is a valibot union, and a failure produced "Invalid type: Expected Object but received Object". Fine for a tampered URL. I wouldn't show that to a person.

Patch the list and the count

Every mutation answers with the same thing: fresh renders of the card list and count for each column it touched.

// src/lib/board-patches.tsx
export async function columnPatches(boardId: string, columns: Column[]) {
  const events = [];
  for (const column of new Set(columns)) {
    const cards = await listCards(boardId, column);
    events.push(patchElements(await render(<CardList column={column} cards={cards} />)));
    events.push(patchElements(await render(<ColumnCount column={column} count={cards.length} />)));
  }
  return events;
}

The targets are #cards-<column> and #count-<column>. They never include the new-card form. That choice matters in the next chapter, when these exact patches go to everyone watching the board. If a patch replaced a whole column, it would wipe whatever someone else was halfway through typing.

Moves return both columns. Delete returns removeElements('#card-<id>') plus the column patches. Edit swaps the card for a form with @get('.../edit'), and Cancel swaps it back with ?view=card.

Card order is a REAL position. New cards land at max(position) + 1000. Moving up or down swaps positions with the neighbour inside one db.batch([...]), so a reader never sees two cards at the same spot.

Clearing the form after a submit

Datastar morphs patched elements and keeps live input state, so sending back the same <form> with the default mode can leave the typed title sitting in the box. Patching with mode: 'replace' swaps the whole element and resets it. Playwright confirmed it: the input value was "" after a create.

An XSS card title, rendered inert

I created a card titled <img src=x onerror="window.pwned=1">. It showed up as literal text. There were 0 <img> tags inside the cards and window.pwned was null. An edit to Line one & <b>two</b> came back as Line one &amp; &lt;b&gt;two&lt;/b&gt; in the HTML.

All of that is Hono JSX doing its job: it escapes text and attribute values. The few places that build HTML strings by hand use escapeHtml() or only interpolate my own validation messages.

There's one rule JSX can't enforce for you. Never put user text inside a Datastar expression attribute. data-on:click={@get('${url}')} is safe here only because url is built from server-generated UUIDs. Escaping protects the HTML, but Datastar still evaluates the attribute as JavaScript.

What I skipped

The plan said optimistic updates. I didn't build them. Every action is a round trip that returns patches. Locally that's a few milliseconds, and in the next chapter you'll see the deployed number. Datastar's data-indicator is where a pending state would go if you want one.

Also, a stale link fails silently. If a card was deleted by someone else, the HTTPException(404) becomes a plain-text 404 and Datastar ignores it. I can live with that for a team board.

Right now only the person who clicked sees the change. Chapter 18 sends those same patches to everyone else on the board.

Live Boards

Two people open the same board. Ada adds a card. Grace should see it without reloading. That's the whole feature, and it's the one I was least sure Void could do cleanly with Datastar.

Chapter 9 showed the two candidates: void/live for fanout, and Durable State for shared state under a name. I couldn't pick between them from the docs, so I built both, measured both, and kept one. The ch18-spikes tag has both side by side (the board page picks one with ?live=a|b). The ch18 tag has only the winner.

The shared design

Both spikes share everything except the transport.

Every mutation from Chapter 17 calls notifyBoard(boardId, columns) after its D1 write. The notice is tiny:

// src/lib/live/notices.ts
/** What a mutation tells live viewers: which columns of a board changed. */
export type BoardNotice = { columns: Column[]; at: number };

The board page opens one long-lived Datastar stream:

<div data-init={`@get('/boards/${board.id}/live', {retry: 'always', retryMaxCount: 1000})`}></div>

GET /boards/:id/live turns each notice into fresh columnPatches() for the touched columns, queried from D1 per viewer. A new connection starts with a full three-column snapshot, so a missed event is harmless.

Why send notices and not rendered HTML? void/live caps an event at 64 KiB. A card renders to about 1.2 KB, so a column of around 50 cards would blow it. Rendering per viewer also keeps auth simple, since each viewer's stream runs under their own session. The cost is one D1 query per touched column, per viewer, per change.

The patches only target #cards-<col> and #count-<col>, as Chapter 17 set up. In the browser, Grace's half-typed draft ("grace draft") survived Ada's live update.

Spike A: bridging void/live

void/live speaks its own envelope (event: message with a JSON body), meant for the browser helper connectLiveStream(). Datastar can't read that, and an API-only app has no client bundle. So the Worker route opens the live connection server-side, subscribes on the viewer's behalf, parses envelopes and writes Datastar patches into its own stream.

There's no server-side subscribe API. live.connect() reads a connectionId from the request URL and live.control() reads its operations from the request body. A GET handler has neither, so I built a fake context:

// src/lib/live/spike-a.ts (ch18-spikes)
// live.connect()/control() read the connection ID and the subscribe operations
// from ctx.req.raw, and there's no server-side subscribe API. To subscribe on
// the viewer's behalf we hand them a minimal context with a request we built.
function contextFor(c: CloudContext, request: Request) {
  return { req: { raw: request }, env: c.env, get: (key: string) => c.get(key as never) } as unknown as CloudContext;
}

It works because live only touches ctx.req.raw, ctx.env and ctx.get('user'). I found that by reading node_modules/void/dist/live-*.mjs. It still relies on internals.

Spike B: a Durable State feed

One Durable Object per board. It numbers each notice, keeps the last 100 in its persisted state, and pushes them to the SSE streams it holds open. This is the version I kept:

// durable-objects/board-feed.ts
const LOG_SIZE = 100;

// Streams can't be persisted; keep them per object instance, in memory.
const listeners = new Map<string, Set<SseStream>>();

const frame = (entry: Entry) => ({ event: 'board', id: String(entry.seq), data: JSON.stringify(entry) });

function parseLastEventId(request: Request): number | null {
  const header = request.headers.get('last-event-id');
  // Careful: Number(null) is 0, which would look like "replay from the start".
  if (header === null || !/^\d+$/.test(header)) return null;
  return Number(header);
}

export const BoardFeed = defineDurableState({
  initialState: { seq: 0, log: [] as Entry[] },
  methods: {
    publish(context, notice: BoardNotice) {
      const entry: Entry = { ...notice, seq: context.state.seq + 1 };
      context.state.seq = entry.seq;
      context.state.log = [...context.state.log.slice(1 - LOG_SIZE), entry];
      const open = listeners.get(context.id.toString()) ?? new Set();
      for (const stream of open) stream.send(frame(entry)).catch(() => open.delete(stream));
      return { seq: entry.seq, listeners: open.size };
    },
  },
  fetch(context, request) {
    const key = context.id.toString();
    const { seq, log } = context.state;
    const lastId = parseLastEventId(request);
    const oldest = log[0]?.seq ?? seq + 1;
    // Replay only if every missed entry is still in the log.
    const canReplay = lastId !== null && lastId <= seq && lastId >= oldest - 1;

    return eventStream(
      async (stream) => {
        const open = listeners.get(key) ?? new Set<SseStream>();
        listeners.set(key, open);
        open.add(stream);
        try {
          if (canReplay) {
            for (const entry of log) if (entry.seq > lastId) await stream.send(frame(entry));
          } else {
            await stream.send({ event: 'snapshot', id: String(seq), data: String(seq) });
          }
          await stream.closed;
        } finally {
          open.delete(stream);
          if (open.size === 0) listeners.delete(key);
        }
      },
      { signal: request.signal },
    );
  },
});

That Number(null) comment is scar tissue. My first version used Number(request.headers.get('last-event-id')). With no header that's 0, which looked like "replay from 0". With an empty log nothing was sent and the stream sat there, open and silent. I suspected Durable State's fetch for a while before I found it. Now 1 (older than the log), 99999 and abc all get a snapshot stamped with the current seq.

The Worker route

The route forwards the browser's Last-Event-ID to the board's object and turns frames into column patches:

// routes/boards/[boardId]/live.ts (trimmed)
const MAX_STREAM_MS = 5 * 60_000;

export const GET = defineHandler(async (c) => {
  const { user, board } = await requireBoard(c);
  const lastEventId = getLastEventId(c.req.raw);

  return eventStream(
    async (stream) => {
      const stop = new AbortController();
      void stream.closed.then(() => stop.abort());
      const lifetime = setTimeout(() => void stream.close(), MAX_STREAM_MS);
      try {
        for await (const message of await subscribeToFeed(board.id, lastEventId, stop.signal)) {
          const columns = message.kind === 'snapshot' ? COLUMNS : message.notice.columns;
          const events = await columnPatches(board.id, columns);
          // Put the id on the last patch, so Last-Event-ID only moves on once
          // the whole update has arrived.
          events[events.length - 1] = { ...events[events.length - 1], id: String(message.seq) };
          for (const event of events) await stream.send(event);
        }
      } finally {
        clearTimeout(lifetime);
        stop.abort();
      }
    },
    { signal: c.req.raw.signal },
  );
});

The id goes on the last patch of each update, so Datastar's last-event-id only moves on once the whole update has arrived. A drop halfway through means the retry asks for that update again.

subscribeToFeed() is a plain BoardFeed.get(boardId).fetch(...) with the header, read through a small SSE parser. That parser takes an AbortSignal that cancels the reader while a read is pending, because a locked body can't be cancelled from outside.

The measurements

Local dev, Miniflare, one MacBook. These are not production numbers. Two signed-in clients on one board, 20 card creations by Ada, timed from POST start to the patch arriving on each stream:

A: void/live bridge

B: Durable State feed

POST create-card p50 / p95

15.9 / 40.8 ms

11.8 / 27.3 ms (final code: 17.8 / 34.1)

Patch at both viewers p50 / p95

15.5 / 40.5 ms

11.6 / 27.0 ms (final: 17.3 / 33.7)

Browser: Grace sees Ada's card

64 ms

56 ms (final: 61 ms)

Reconnect after 3 missed changes

full snapshot (6 patches)

replay of exactly the 3 missed updates

260 concurrent viewers on one board

256 OK, 4 rejected TOPIC_FULL

260 OK

One publish to 256/260 viewers

POST 312 ms

POST 645 ms

300 sequential open/close cycles

10.4 s, 31 failed TOPIC_FULL

3.2 s, 0 failed

Freed slot after 256 viewers leave

~10.2 s until a 257th could subscribe

n/a (no cap)

Dev-server restart mid-session

next change shown 2.4 s after restart

same, 2.4 s, and seq survived

Non-member stream

404

404

The 260-viewer publish times are mostly 260 streams re-querying one local SQLite file at once. They say nothing about production D1.

Why Durable State won

The 256 cap bites early. In A, a closed connection keeps its topic slot for about 10 seconds. A burst of reconnects double-counts viewers. I got 31 TOPIC_FULL failures out of 300 sequential reconnects from a single user. The cap can't go above 256.

Replay works. Datastar 1.0.5 tracks SSE id: and sends last-event-id on retry. B replays from its log. void/live sets no SSE ids and stores no events (at-most-once by design), so A only ever gets snapshots.

Less glue. A needs the fake context and an envelope parser. B is a fetch to my own object.

A has real strengths. It's less code if you don't need replay and stay under about 100 viewers per topic, and it multiplexes many topics over one connection.

What B costs

  • The board's Durable Object stays in memory while anyone is watching. Streaming responses don't hibernate the way WebSockets can. Expect duration charges per active board on Workers Paid. I haven't measured them.
  • Dead connections are found lazily, on the object's next write (a publish or the 15-second keep-alive). The listeners count is briefly wrong.
  • One object per board serializes every publish for that board. Fine for a team. Wrong for a 10,000-viewer broadcast.
  • Durable State persists the whole state after every call, so keep the log small. Notices are about 60 bytes.
  • The server closes each stream after 5 minutes. Datastar's retry: 'always' reconnects (the default 'auto' only retries on errors), and retryMaxCount: 1000 covers a long session.

void prepare added the BOARD_FEED binding to void.lock.json. Commit that file.

On real Cloudflare

Everything above ran in Miniflare. On 2026-12-01 I deployed the app to my own account (Chapter 21 has the deploy) and repeated the key checks against the live Worker:

  • Two viewers had the same board open at once. A newly created card arrived at both of them as a patch carrying id: 1.
  • A card titled <b>&</b> arrived escaped in the patch.
  • Reconnecting with Last-Event-ID: 0 replayed exactly the missed update, id: 1, with no snapshot.
  • The card POST took about 0.44 s from my client.

That 0.44 s was measured from my machine, so it includes the network round trip. I didn't measure how long Cloudflare keeps a streaming response open, or what happens to open streams during a deploy. The 5-minute cap plus Datastar's retry is my hedge until I do.

The board is live now. Chapter 19 hangs files off the cards and moves slow work into a queue.

Attachments and Background Jobs

Cards need files. A screenshot of the bug, a PDF of the contract, a CSV someone wants eyes on. And some work shouldn't happen inside the request that triggered it, like checking what a file really is or emailing everyone a summary at 7 a.m.

This chapter adds both: R2 uploads with a queue that processes them, and a nightly digest cron. The code is at the ch19 tag. Chapter 8 covered crons and queues in isolation. Here they do real jobs, and one of them broke in a way I didn't expect.

The upload route

The card panel gets a plain multipart form. Datastar's contentType: 'form' sends FormData, so files go as multipart with no extra code:

// src/views/attachments.tsx (trimmed)
<form data-on:submit={`@post('${url}', {contentType: 'form'})`} enctype="multipart/form-data">
  <input type="file" name="file" accept="image/png,image/jpeg,image/gif,image/webp,application/pdf,text/plain,text/markdown,text/csv" />
  <p class="error">{error ?? ''}</p>
  <button type="submit">Upload</button>
</form>

The accept list is a hint for the file picker. The server does the actual checking:

// routes/boards/[boardId]/cards/[cardId]/attachments.tsx (trimmed)
export const POST = defineHandler(async (c) => {
  const { user, board, card } = await loadCard(c);

  // Refuse obviously oversized bodies before buffering them.
  const declared = Number(c.req.header('content-length') ?? 0);
  if (declared > MAX_BYTES + 64 * 1024) return listPatch(board.id, card.id, 'Files can be at most 5 MB.');

  const check = checkUpload((await c.req.parseBody()).file);
  if (!check.ok) return listPatch(board.id, card.id, check.error);

  const { file } = check;
  const key = storageKey(board.id, card.id);
  await storage.put(key, await file.arrayBuffer(), {
    httpMetadata: { contentType: file.type },
    customMetadata: { filename: file.name },
  });
  const attachment = await createAttachment({
    cardId: card.id,
    uploaderId: user.id,
    storageKey: key,
    filename: file.name.slice(0, 200),
    contentType: file.type,
    size: file.size,
  });
  await queues.attachments.send({ attachmentId: attachment.id });
  return listPatch(board.id, card.id);
});

checkUpload() wants a non-empty File, at most 5 MB, with a MIME type on an allow-list: PNG, JPEG, GIF, WebP, PDF, plain text, Markdown and CSV. The storage key is mine (attachments/<board>/<card>/<uuid>). The filename only goes in metadata and in D1.

With curl, a 6 MB big.txt came back with "Files can be at most 5 MB." A page.html got Files of type "text/html" aren't allowed. Both showed inline in the browser too.

Checking the bytes in a queue

The browser tells you the type. It can lie. So the row starts as pending, and a queue consumer reads the object back from R2 and checks its first bytes against the declared type:

// src/lib/attachments.ts (trimmed)
export function sniffMatches(bytes: Uint8Array, contentType: string): boolean {
  const starts = (...sig: number[]) => sig.every((b, i) => bytes[i] === b);
  switch (contentType) {
    case 'image/png':
      return starts(0x89, 0x50, 0x4e, 0x47);
    case 'image/jpeg':
      return starts(0xff, 0xd8, 0xff);
    case 'application/pdf':
      return starts(0x25, 0x50, 0x44, 0x46);
    // ...gif, webp
    default:
      return true; // text types: nothing reliable to sniff
  }
}

The consumer then writes a one-line preview (PNG dimensions from the header, a PDF page count, a text excerpt) and marks the row ready or failed:

// queues/attachments.ts (trimmed)
export const maxRetries = 3;
export const retryDelay = 10;

export default defineQueue<AttachmentJob>(async (batch) => {
  for (const message of batch.messages) {
    const { attachmentId } = message.body;
    try {
      const attachment = await getAttachment(attachmentId);
      if (!attachment) {
        message.ack();
        continue;
      }
      const object = await storage.get(attachment.storageKey);
      if (!object) throw new Error('object missing from storage');
      const bytes = new Uint8Array(await object.arrayBuffer());

      if (!sniffMatches(bytes, attachment.contentType)) {
        await finishAttachment(attachmentId, { status: 'failed', preview: "Contents don't match the file type." });
      } else {
        await finishAttachment(attachmentId, { status: 'ready', preview: describe(bytes, attachment.contentType) });
      }
      message.ack();
    } catch (error) {
      if (message.attempts > maxRetries) {
        await finishAttachment(attachmentId, { status: 'failed', preview: 'Processing failed.' });
        message.ack();
      } else {
        message.retry({ delaySeconds: retryDelay });
      }
    }
  }
});

That last branch exists because Void configures no dead-letter queue (Chapter 8). Without it, a message that runs out of retries is dropped and the row stays pending forever.

Three uploads, three outcomes. notes.txt went ready with a text excerpt as its preview: "Launch checklist - write post - record demo". A generated 640×480 red.png became "PNG image, 640×480". And fake.png, a <script> declared as image/png, ended up failed with "Contents don't match the file type." Locally the consumer ran right after send(), and all three were done within about a second.

How does the page find out? While anything is pending, the list carries a poll:

<ul class="list" {...(pending ? { 'data-on-interval__duration.1s': `@get('${url}')` } : {})}>

In the browser, red.png showed pending, the 1-second poll flipped it to ready · PNG image, 640×480, and the attribute was gone from the DOM afterwards.

A download route that won't render anything

Uploaded files can contain HTML or script. The download route checks membership through a join (attachment → card → board members) and then sends headers that stop the browser from treating the file as a page:

// routes/attachments/[attachmentId].ts (trimmed)
const headers = new Headers();
object.writeHttpMetadata(headers);
headers.set('etag', object.httpEtag);
headers.set('X-Content-Type-Options', 'nosniff');
headers.set('Content-Security-Policy', "default-src 'none'; sandbox");
headers.set('Content-Disposition', `attachment; filename*=UTF-8''${encodeURIComponent(attachment.filename)}`);
headers.set('Cache-Control', 'private, no-store');
return new Response(object.body, { headers });

A member got a 200 with the right bytes. A non-member got a 404. Signed out, a 302 to sign-in.

One more thing: deleting a card cascades its attachment rows in D1, but R2 objects don't cascade. The card delete handler now calls storage.delete(keys) first. With 4 attachments on a card, the local bucket went from 6 objects to 2. Deleting a whole board still orphans its files. That's on the checklist in Chapter 21.

The nightly digest

// crons/nightly-digest.ts (trimmed)
// 07:00 UTC every day.
export const cron = '0 7 * * *';

export default defineScheduled(async (controller) => {
  const now = new Date(controller.scheduledTime);
  const since = new Date(now.getTime() - 24 * 60 * 60 * 1000);
  const activity = await loadActivity(since);
  // ...group memberships by email, then:
  for (const member of byMember.values()) {
    const digest = buildDigest(member, member.boards.map((id) => activity.get(id)!).filter(Boolean), now);
    if (!digest) continue;
    const result = await sendEmail({ to: digest.to, subject: digest.subject, text: digest.text });
    if (result.ok) sent++;
    else logger.error('digest.failed', { to: digest.to, result: JSON.stringify(result) });
  }
});

buildDigest() is pure and tested. It returns null when nothing happened on a member's boards, so quiet days send nothing.

I triggered it with the dev token from Chapter 8:

TOKEN=$(cat .void/dev-trigger-token)
curl -X POST http://localhost:5173/__void/scheduled \
  -H 'Content-Type: application/json' -H "x-void-dev-trigger: $TOKEN" \
  -d '{"cron":"0 7 * * *","scheduledTime":'"$(date +%s000)"'}'

200 {"ok":true}, a digest.done log line with "members":2,"sent":2, and two messages in the local inbox at /__void/inbox: "Void Board digest for 2026-12-01", one to Ada and one to Grace. Nothing left my machine.

The 100-parameter wall

My first loadActivity() collected card IDs and used inArray(comments.cardId, cardIds). After the Chapter 18 load tests the board had more than 100 cards, and the cron died:

D1_ERROR: too many SQL variables at offset 360: SQLITE_ERROR

D1 caps bound parameters at 100 per statement. The error came wrapped in AggregateError: Scheduled jobs failed: crons/nightly-digest.ts, and /__void/scheduled returned a 500.

The fix was to stop passing lists. The rewrite uses joins and groupBy with a fixed parameter count:

// src/lib/digest.ts (one of the three grouped queries)
db
  .select({ boardId: cards.boardId, n: count() })
  .from(comments)
  .innerJoin(cards, eq(cards.id, comments.cardId))
  .where(gte(comments.createdAt, since))
  .groupBy(cards.boardId),

Go look for inArray over any list a user can grow. It works fine on a seeded board with four cards and fails on a busy one.

Real email needs setup I didn't do

Locally sendEmail lands in the dev inbox. A real deploy needs void email setup --platform cloudflare, a sending domain in your Cloudflare account, and Workers Paid for arbitrary recipients (Chapter 10). I haven't run it. My sender is still digest@example.com, and on the first deploy Void noticed: there was no zone for example.com in the account, so it printed "deploying without email" and carried on.

Without the binding, sendEmail returns BINDING_MISSING as a result instead of throwing, so the cron logs digest.failed and keeps going. I also haven't seen real Queues retry timing or a cron fire on its schedule. Only the manual triggers.

Files work and the slow parts run in the background. Chapter 20 adds the last feature: a streamed AI summary of a card's comments.

An AI Touch

A card with 30 comments is a card I don't want to reopen. So the last feature is a "Summarize comments" button: one click, and a short summary streams into the card panel a few words at a time.

I'll say this up front. I didn't run a real Workers AI call for this chapter. Chapter 10 explained why: Workers AI has no local simulator, and this build never connected an AI binding. So the design puts the model behind an interface, ships a fake that runs anywhere, and keeps the real provider tested against a mock. The code is at the ch20 tag.

The interface

// src/lib/ai/summarizer.ts
export type SummaryInput = {
  title: string;
  comments: Array<{ author: string; body: string }>;
};

/** Anything that can stream a summary, token by token. */
export interface Summarizer {
  readonly name: string;
  stream(input: SummaryInput, signal?: AbortSignal): AsyncIterable<string>;
}

Same file, the prompt. It asks for 2 or 3 short sentences: what was decided and what's still open, plain text, no preamble.

The picker reads one env value:

// env.ts
import { defineEnv, oneOf } from 'void/env';

export default defineEnv({
  // "fake" needs no Cloudflare account; "workers-ai" calls Workers AI (remote, metered).
  AI_PROVIDER: oneOf(['fake', 'workers-ai']).default('fake'),
});
// src/lib/ai/index.ts
export function getSummarizer(): Summarizer {
  return env.AI_PROVIDER === 'workers-ai' ? workersAiSummarizer() : fakeSummarizer();
}

A typo fails loudly. AI_PROVIDER=nope stopped the Worker at boot with AI_PROVIDER: Expected one of fake, workers-ai, got "<redacted>". Void redacts the value even in its own error message.

The fake is the default

// src/lib/ai/fake.ts
export function fakeSummarizer(options: { delayMs?: number } = {}): Summarizer {
  const delayMs = options.delayMs ?? 25;
  return {
    name: 'fake',
    async *stream(input: SummaryInput, signal?: AbortSignal) {
      const people = [...new Set(input.comments.map((c) => c.author))];
      const points = input.comments.map((c) => c.body.split(/(?<=[.!?])\s/)[0]);
      const text = input.comments.length
        ? `${input.comments.length} comments from ${people.join(' and ')}. ${points.join(' ')}`
        : 'No comments yet.';
      for (const word of text.split(' ')) {
        if (signal?.aborted) return;
        if (delayMs) await new Promise((resolve) => setTimeout(resolve, delayMs));
        yield `${word} `;
      }
    },
  };
}

It's a dumb summarizer on purpose. It quotes the first sentence of each comment, one word every 25 ms. That's enough to build and test the whole streaming UI with no account, and it's deterministic, so tests can assert on the exact output.

The Workers AI provider

// src/lib/ai/workers-ai.ts (trimmed)
export const SUMMARY_MODEL = '@cf/meta/llama-3.1-8b-instruct-fast';

export function workersAiSummarizer(): Summarizer {
  return {
    name: 'workers-ai',
    async *stream(input: SummaryInput, signal?: AbortSignal) {
      // Rejects with UsageLimit (void/limits) when the account or platform is over quota.
      const body = (await ai.run(SUMMARY_MODEL, {
        messages: summaryMessages(input),
        max_tokens: 200,
        stream: true,
      })) as ReadableStream<Uint8Array>;
      for await (const frame of readSse(body, signal)) {
        const token = tokenFromFrame(frame.data);
        if (token === null) return;
        if (token) yield token;
      }
    },
  };
}

With stream: true, ai.run() resolves to a stream of SSE bytes. I parse it with the same readSse() from Chapter 18. tokenFromFrame() handles both {"response": "..."} frames and OpenAI-style choices[0].delta.content frames, and stops at [DONE].

Three honest caveats on that code. TypeScript types the result as the model's output union, so there's a cast. The frame shapes come from Cloudflare's docs, and the tests use a fixture, so they're unverified against the live service. And I picked the model ID from what I know of the Workers AI catalog. Listing models with ai.models() needs the binding, which I didn't have.

The quota

Models cost money, and a button is easy to mash. Each user gets 10 summaries an hour, counted by a small Durable State object keyed by user ID:

// durable-objects/summary-quota.ts
export const SummaryQuota = defineDurableState({
  initialState: { windowStart: 0, used: 0 },
  methods: {
    take(context, limit: number, windowMs: number) {
      const now = Date.now();
      if (now - context.state.windowStart >= windowMs) context.state = { windowStart: now, used: 0 };
      if (context.state.used >= limit) {
        return { ok: false as const, retryAt: new Date(context.state.windowStart + windowMs).toISOString() };
      }
      context.state.used += 1;
      return { ok: true as const, remaining: limit - context.state.used };
    },
  },
});

Over the limit, the route throws UsageLimit from void/limits. That's the same error type void/ai rejects with when an account or platform runs out, so one catch handles my quota and Cloudflare's:

async function takeQuota(userId: string) {
  const result = await SummaryQuota.get(userId).take(SUMMARIES_PER_HOUR, 60 * 60_000);
  if (!result.ok) throw new UsageLimit({
      resource: 'ai',
      reason: 'rate_limit',
      message: 'Summary limit reached for this hour.',
      retryAt: result.retryAt,
    });
}

message is required. TypeScript told me so. The AI guide only shows how to catch it.

Streaming it into the page

The button:

<button data-on:click={`@post('${url}/summary')`} data-indicator="summarizing" data-attr:disabled="$summarizing">
  Summarize comments
</button>

The route is an eventStream that re-renders #summary after every token:

// routes/boards/[boardId]/cards/[cardId]/summary.tsx (trimmed)
return eventStream(
  async (stream) => {
    const send = async (text: string, note?: string) =>
      stream.send(patchElements(await render(<Summary text={text} note={note} />)));
    try {
      await takeQuota(user.id);
      await send('…', `Summarizing ${comments.length} comments`);
      let text = '';
      const started = Date.now();
      for await (const token of summarizer.stream(
        { title: card.title, comments: comments.map((c) => ({ author: c.author ?? 'Someone', body: c.body })) },
        stream.signal,
      )) {
        text += token;
        await send(text.trim(), 'Writing…');
      }
      await send(text.trim(), `Summarized by ${summarizer.name} in ${Date.now() - started} ms`);
    } catch (error) {
      if (error instanceof UsageLimit) {
        const at = error.retryAt ? ` Try again after ${error.retryAt.slice(11, 16)} UTC.` : '';
        await send('', `You've used your ${SUMMARIES_PER_HOUR} summaries for this hour.${at}`);
        return;
      }
      if (stream.signal.aborted) return;
      await send('', 'Summarizing failed. Try again in a moment.');
    }
  },
  { signal: c.req.raw.signal },
);

Catching UsageLimit inside the stream matters. Uncaught, Void turns it into a structured 429. Datastar ignores non-200 responses, so the user would see nothing at all.

In the browser, the button went disabled while streaming and I counted 19 distinct renders of #summary before the final one: "3 comments from Grace and Ada. Lead with the live board demo, it sells itself. Agreed. Add a short FAQ about pricing at the end." Then "Summarized by fake in 670 ms". Calls 1 to 10 worked and call 11 said "You've used your 10 summaries for this hour. Try again after 18:01 UTC." Grace had her own 10.

Re-rendering the whole block per token is simple and morphs cleanly. For long outputs, appending tokens into a <span> with mode: 'append' would send less.

What real Workers AI needs

I read the plugin source before trying anything. vite build always adds an AI binding when a file imports void/ai. vite dev binds the remote Workers AI only when the project is saved with the direct Cloudflare target in .void/project.json. This project had no saved target during the build, so dev printed [void] AI requires authentication. Run \void account login`, then restart the dev server.and carried on. WithAI_PROVIDER=workers-ai, a summary failed before any network call with ai: Not available. Configure a Workers AI binding (env.AI)...`, and the route showed its generic error.

To run it for real:

  1. A Cloudflare account with Workers AI. It's metered in neurons with a daily free allowance, so check current pricing.
  2. Point the project at the account: npx void connect --platform cloudflare, a first void deploy --platform cloudflare, or CLOUDFLARE_API_TOKEN with Workers AI permissions in CI.
  3. For dev against the real model, put AI_PROVIDER=workers-ai in the root .env. Every call bills your account.
  4. For production, npx void secret put AI_PROVIDER with the value workers-ai. Leaving it on fake is fine for a demo.
  5. Confirm the model ID with ai.models() once you have the binding.

The 5 tests in tests/ai.test.ts cover the fake's output and abort handling, plus the Workers AI provider with vi.mock('void/ai') feeding it a fixture stream: tokens join up, ai.run gets the expected model and inputs, and UsageLimit passes through.

That's every feature. Chapter 21 tests the whole thing, ships it to Cloudflare, and covers what operating it looks like.

Test, Ship, Operate

The board does everything I planned. Now it needs tests I trust, a build that passes on a fresh clone, and a real deploy. This chapter covers all three, plus the checklist I worked through before shipping. The code is at the ch21 tag.

Handler tests without a Worker

Chapter 11 showed the split: the dev server runs your code in Miniflare, the test runner runs it in plain Node. I wanted handler tests that exercise the real route modules, real SQL and real validation, without a Worker in sight.

The trick has three parts.

The database is real SQLite. Each test gets an in-memory better-sqlite3 database with the app's actual migration files applied:

// tests/helpers/test-db.ts
export function createTestDb() {
  const sqlite = new Database(':memory:');
  sqlite.pragma('foreign_keys = ON');
  const dir = new URL('../../db/migrations/', import.meta.url);
  for (const file of readdirSync(dir).filter((f) => f.endsWith('.sql')).sort()) {
    for (const statement of readFileSync(new URL(file, dir), 'utf8').split('--> statement-breakpoint')) {
      if (statement.trim()) sqlite.exec(statement);
    }
  }
  const db = drizzle(sqlite);
  // D1 has db.batch(); better-sqlite3 doesn't. Run the statements in order.
  return Object.assign(db, {
    batch: async (queries: PromiseLike<unknown>[]) => {
      const results = [];
      for (const query of queries) results.push(await query);
      return results;
    },
  });
}

Same dialect, same schema, foreign keys on. Queries and constraints run for real. I pinned drizzle-orm@0.45.4 and better-sqlite3@13.2.0 as devDependencies to match what Void itself installs.

Bindings are mocked with vi.mock. void/db becomes Drizzle's operators plus a db that points at the test's SQLite:

// tests/handlers.test.ts (trimmed)
vi.mock('void/db', async () => ({
  ...(await vi.importActual<object>('drizzle-orm')),
  db: new Proxy({}, { get: (_, key) => Reflect.get(state.db, key) }),
}));

// The live feed is a Durable Object, which doesn't exist in Node.
const notifyBoard = vi.fn(async () => {});
vi.mock('../src/lib/live/notify', () => ({ notifyBoard }));

void/storage and void/queues get small in-memory fakes. The live notifier is mocked at my own module, since Durable Objects don't exist in Node.

Auth isn't mocked at all. requireAuth only reads c.get('user'). And defineHandler(fn) with one argument returns fn unchanged (I checked node_modules/void/dist/handler-*.mjs). So route exports mount straight onto a bare Hono app behind a middleware that sets the user:

// tests/helpers/app.ts (trimmed)
export function testApp(
  routes: Array<[method: string, path: string, handler: Handler]>,
  context: { user?: unknown; auth?: unknown } = {},
) {
  const app = new Hono();
  app.use(async (c, next) => {
    c.set('user' as never, (context.user ?? null) as never);
    if (context.auth) c.set('__voidAuth' as never, context.auth as never);
    await next();
  });
  for (const [method, path, handler] of routes) {
    app.on(method, path, async (c) => {
      const result = await handler(c as never);
      return result instanceof Response ? result : c.json(result);
    });
  }
  return app;
}

withValidator handlers still validate, so the move route's JSON 400 is tested too. A test then reads like a request:

it('creates a card, patches the column and notifies live viewers', async () => {
  const res = await cardsApp(asUser(ada)).request('/boards/board-1/cards', {
    method: 'POST',
    headers: datastarHeaders,
    body: form({ column: 'todo', title: '<b>Ship it</b>' }),
  });
  const body = await res.text();
  expect(body).toContain('&lt;b&gt;Ship it&lt;/b&gt;'); // escaped
  expect(body).toContain('data: mode replace'); // fresh form for the author
  expect(notifyBoard).toHaveBeenCalledWith('board-1', ['todo']);
});

Queue consumers and crons are plain default exports, so tests call them with a fake batch or a fake controller. The cron test uses the real sendEmail, captured by createEmailTestHarness from void/email/testing.

That test caught something. Under Vitest, email.from from void.config.ts isn't applied, and sendEmail returned INVALID_FROM. In dev the plugin injects it. The fix was a tiny src/email-sender.ts that exports EMAIL_FROM, imported by both the config and the cron.

npm test: 7 files, 44 tests, about half a second. SSE framing, the SSE reader, upload checks and sniffing, the digest, the AI providers, 11 handler tests and the cron.

One command before every deploy

"check": "npm run typecheck && npm test && npm run build"

npm run check passed: typecheck, 44 tests, then a production build with a 992 KB Worker (243 KB gzip). The build's worker.config.json listed every binding the app needs: D1, R2, the attachments queue, both Durable Object classes and static assets, plus the 0 7 * * * cron.

I also cloned the repo fresh and checked out every tag. That found one more bug. On a fresh checkout, void prepare has to run twice before tsc passes. The first run generates the auth schema but leaves @auth-schema out of .void/tsconfig.json, so tsc fails with TS2307: Cannot find module '@auth-schema'. The second run adds it. From ch21 on, the postinstall script is void prepare && void prepare. Dev and build were fine on every tag either way.

The production checklist

What I checked before the first deploy:

  • Migrations drift-free. npx void db generate prints "No schema changes". The auth tables live in the same migration.
  • void.lock.json committed. It holds the Durable Object bindings and migration tags. Never reorder or delete its DO entries after a deploy.
  • Durable State names pinned (board-feed, summary-quota), the names void info suggested, so moving a file can't orphan stored state.
  • Secrets. BETTER_AUTH_SECRET is created by void deploy if it's missing. AI_PROVIDER defaults to fake.
  • Sender address. Still digest@example.com. Real mail needs void email setup --platform cloudflare first (Chapter 19).
  • D1 read replication off, the default. The live patches assume reads see the write that triggered them.
  • Uploads. The 5 MB cap is in the handler. A deleted board's R2 files are orphaned. Add a sweep before that matters.
  • Live streams. 5-minute close plus Datastar's retry. Watch Durable Object duration costs.

The first deploy

On 2026-12-01 I shipped it to my own Cloudflare account. First the pre-flight:

npm run check
npx void db status       # local: applied, nothing pending
npx void db generate     # No schema changes, nothing to migrate
npx void deploy --platform cloudflare

Deploy built the Worker, then saved a D1 restore point before touching the database and printed the command to roll it back:

● Saved a D1 restore point before applying 1 migration.
  To undo these migrations, restore this point (discards every later write):
    void db restore --platform cloudflare --bookmark=<id>

It applied the 1 migration, published, and finished with:

https://void-board.<subdomain>.workers.dev
  Worker: void-board
  D1 migrations up to date
  1 cron job scheduled
  1 queue configured

It also noticed my example.com sender had no zone in the account and deployed without email. That's the setup Chapter 19 skipped.

Then I committed void.lock.json. The deploy had written the account ID, the D1 database (name and ID) and the R2 bucket name into it, next to the Durable Object entries void prepare added earlier. Commit it after the first deploy, every time.

Operating it

Chapter 12 walked through these commands from the docs. Here's how they behaved on a real app.

void project status first answered "Not logged in. Run void account login first." Deploying with --platform cloudflare doesn't save a target. After void connect --platform cloudflare once, it showed the live version with 1 migration.

void project logs is a live tail with no history. I requested / and /nope while it ran, and both showed as ok. The app answered /nope with a 404 page, but the Worker didn't throw, so the tail calls it fine. Use --level error for exceptions, and don't expect it to surface 404s.

Chapter 18 has the live checks I ran against the deployed board: two viewers, the escaped title, the Last-Event-ID replay.

The rollback drill I didn't run

I planned a rollback drill. I didn't execute it. Here's the procedure from the Void docs, untested:

npx void project rollback <deployId> --platform cloudflare            # code only
npx void db restore --bookmark <bookmark> --platform cloudflare       # data, discards later writes

Rollback doesn't undo migrations. A restore throws away every write after the bookmark. So the safe habit is migrations the previous version of the code can live with, and the bookmark from each deploy saved somewhere you'll find it.

That's Part 2: a real app, built from a skeleton to a deploy. Part 3 is the toolkit, and it starts with Chapter 22, "Void with Astro."

Void with Astro

Everything so far has been a native Void app. Void also has a framework mode, and Astro is one of the frameworks it supports. Astro keeps its pages, its build and its Cloudflare adapter. Void plugs into Astro's Vite config and adds the database, migrations, KV, storage, crons and deploys.

This site runs Astro on Cloudflare Workers, so I wanted to know what the combination takes. I built a small test app from the Astro integration page, added a database-backed API route and a page, and ran it in dev and as a production build. The full write-up is in Using Void with Astro. This chapter is the condensed version, plus what Part 1 taught me about the limits.

I tested with Astro 7.4.13, @astrojs/cloudflare 14.4.9, Void 1.12.0, Vite 8.4.0 and Node 24.22.3. I did not deploy it, so anything about deploys below comes from the docs.

Before you install

Astro 7 or later, because Void needs Vite 8. And the Node trap from chapter 1 hits here too. On Node 24.14.1, npm install -D void quietly gave me void 0.10.13, and the first build died complaining that .void-wrangler.jsonc didn't exist. That error points you at config files. The fix was Node.

node --version   # needs 24.22+ or 26.12+

Two config files

Add the packages to an Astro project:

npm create astro@latest my-app
cd my-app
npm install -D @astrojs/cloudflare void

Then point the Cloudflare adapter at a config file Void manages, and add voidPlugin() to Astro's Vite plugins:

// astro.config.mjs
import cloudflare from '@astrojs/cloudflare';
import { defineConfig } from 'astro/config';
import { voidPlugin } from 'void';

export default defineConfig({
  adapter: cloudflare({ configPath: './.void-wrangler.jsonc' }),
  vite: { plugins: [voidPlugin()] },
});

Worker settings go in void.config.ts. The nodejs_als flag is required:

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

export default defineConfig({
  cloudflare: {
    name: 'my-app',
    compatibility_date: '2026-02-24',
    compatibility_flags: ['nodejs_als'],
  },
});

You don't write .void-wrangler.jsonc. The first astro dev or astro build generates it from void.config.ts, which the docs never mention. Once I added a schema, it looked like this:

{
  "name": "my-app",
  "compatibility_date": "2026-02-24",
  "compatibility_flags": ["nodejs_als"],
  "d1_databases": [
    { "binding": "DB", "database_name": "default", "database_id": "local" }
  ]
}

That D1 binding is resource detection at work. I never declared it. Void saw db/schema.ts and wrote it, the same inference chapter 5 showed in a native app.

The database from Astro code

The schema is the same file a native app uses, with Void's Drizzle helpers:

// db/schema.ts
import { sql } from 'void/db';
import { integer, sqliteTable, text } from 'void/schema-d1';

export const notes = sqliteTable('notes', {
  id: integer('id').primaryKey({ autoIncrement: true }),
  body: text('body').notNull(),
  createdAt: text('created_at')
    .notNull()
    .default(sql`(datetime('now'))`),
});

npx void db generate wrote the migration and npx void db migrate applied it locally.

In Astro, two imports do the work. @schema resolves to your schema file, and db comes from void/db. And anything that touches a binding needs prerender = false, or Astro tries to run it at build time:

// src/pages/api/notes.ts
import { notes } from '@schema';
import type { APIRoute } from 'astro';
import { db, desc } from 'void/db';

export const prerender = false;

export const GET: APIRoute = async () => {
  const rows = await db.select().from(notes).orderBy(desc(notes.id)).limit(20);
  return Response.json(rows);
};

export const POST: APIRoute = async ({ request }) => {
  const { body } = (await request.json()) as { body?: string };
  if (!body?.trim()) return Response.json({ error: 'body is required' }, { status: 400 });
  const [note] = await db.insert(notes).values({ body: body.trim() }).returning();
  return Response.json(note, { status: 201 });
};

The same query works in an .astro page's frontmatter, with the same prerender = false. I posted a note with curl, got 201 and the row back, got a 400 for an empty body, and saw the row render on the page. Then npm run build and astro preview served the same data from the production build.

The dev middleware gotcha

On the first dev run, Void wrote a src/middleware.ts headed "Auto-generated by Void in dev. Do NOT edit. Removed when the dev server stops", and added src/middleware.ts to .gitignore. It uses that file to fire cron and queue handlers locally.

I killed that first server hard. The file and the .gitignore line both stayed. If you write your own src/middleware.ts later, git ignores it and it never reaches a commit.

When my own middleware existed first, Void left it alone and my header still came through. So stop dev with Ctrl+C, and after any hard kill, check .gitignore.

Environment: void/env replaces astro:env

Declare variables in env.ts (chapter 6) and read them with import { env } from 'void/env'. That replaces astro:env. Client values use Void's VITE_* prefix, even though Astro would normally have you reach for PUBLIC_*.

For a raw binding, env from cloudflare:workers still works:

import { env } from 'cloudflare:workers';

const { results } = await env.DB.prepare('SELECT * FROM notes').all();

KV, storage, AI, crons/ and queues/ are documented for framework apps with the same imports. I only tested the database in Astro.

What stays native-only

This is the list that decides whether framework mode works for you. From the Part 1 chapters and the docs:

  • Managed auth (chapter 7). Framework apps use Better Auth directly, through its own Astro integration.
  • WebSockets (.ws.ts routes) and Durable State (chapter 9). The docs exclude both from framework mode.
  • void/live isn't on the framework feature list. I'd treat it as native-only until it is.
  • Inbound email (email/ handlers, chapter 10) is native-only. The local dev inbox for sends returns BINDING_MISSING in Astro.

I didn't test void/sse inside Astro, so check it before you plan around it.

The Part 2 board needed auth, live updates and Durable Objects. That's why it's a native app. A content site with a database and a contact form doesn't need any of them.

Deploying, per the docs

The docs say it's the same flow as a native app: void deploy builds, provisions what it detected, applies migrations and publishes the Worker. Chapter 12 covers the commands and the rollback caveat. I haven't run it against an Astro app, so test it on something you can throw away first.

Would I use it?

For a new Astro app that needs a database, yes. The D1 setup, the binding and the migration workflow came out of one schema file. For an Astro site that's already happy on Wrangler, I'm less sure, and that's the bigger question.

Chapter 23 takes it on: Void, plain Workers, or Astro on Cloudflare, and how I'd choose.

Toolkit: Void, Plain Workers, or Astro on Cloudflare?

Three ways to put an app on Cloudflare Workers, and I've now used all three. This site is Astro on Workers. I've written plain Workers with a hand-kept wrangler.jsonc too. And this guide is a few weeks of Void.

They overlap a lot. Picking well comes down to what the app is and how much young-framework churn you can live with.

Void's pace is the first fact

Void 1.0 reached npm on October 15, 2026 (as 1.0.3, because of the old package name from chapter 1). By November 27 it was at 1.12.2, with 21 published 1.x versions in six weeks. Some of those were same-day patch runs.

That speed shows up in the docs. Here's what I hit while writing Part 1:

  • Workflows are documented but not released. The guide on void.cloud describes void/workflows. In 1.12.2 the import fails with ERR_PACKAGE_PATH_NOT_EXPORTED. The feature landed on the main branch on December 1, and the docs track main.
  • void dev doesn't exist. Some pages mention it. The CLI prints Unknown command 'dev'; the dev server is Vite's.
  • requireAuth is called with and without await. It's synchronous. Both forms work, but the docs disagree with themselves.
  • void/sse splits multi-line strings into several data: lines. Correct SSE, undocumented, and it matters for Datastar.
  • .void-wrangler.jsonc appears from nowhere in framework mode, and the error you get before it exists points at the wrong problem.
  • "Void Cloud" shows up in operator docs, and I found no way to sign up for it.

None of these is a dealbreaker on its own. Each one cost me time, though, and you'll hit new ones on the next release.

Then there's Node. Void 1.x needs ^24.22.0 || >=26.12.0, and on anything older npm quietly installs a pre-1.0 release instead of failing. Your CI image has to be current too.

What Void gives you over Wrangler

The value is real, and it's mostly work you'd otherwise do by hand:

  • Resource inference. Import void/db or void/kv and the binding appears. I never wrote a D1 binding in this whole guide.
  • Migrations on deploy. void deploy applies pending SQL, stops if the schema drifted without a migration, and saves a D1 restore point first with the exact void db restore --bookmark command printed.
  • Auth. Better Auth wired to your D1 database, with requireAuth and sessions, in native apps.
  • Realtime. void/sse, void/live fanout, .ws.ts rooms and Durable State, without writing a Durable Object class from scratch.
  • Background work. A file in crons/ or queues/ becomes a trigger or a consumer, and both run locally.
  • Typed env. env.ts validates secrets before deploy and refuses to ship if a required one is missing.

What plain Workers and Wrangler give you

Control, mostly. Every binding, flag and route is in a file you wrote and can read top to bottom. When something breaks, Cloudflare's own docs describe exactly what you're running, and Wrangler has years of issues and answers behind it.

The cost is the typing Void removes. You create the D1 database, paste its ID, run wrangler d1 migrations apply yourself, and wire every queue and cron trigger by hand. With one binding, that's quick. With eight, it's a long afternoon and a config file only you understand.

The Mastering Cloudflare guide covers this path.

Astro on Cloudflare for content sites

If the app is mostly pages, a blog, docs or a marketing site, I'd start with Astro and the Cloudflare adapter. That's what runs this site, with EmDash as the CMS on D1 and R2. Astro gives you content collections, image handling and a page model built for publishing, none of which Void's native mode tries to be.

And chapter 22 showed you can still add Void to Astro later for the database and migrations, as long as you don't need managed auth, WebSockets, Durable State or inbound email. The Mastering EmDash guide covers the CMS route if you want an admin UI on top.

Side by side

Void (native)

Plain Workers + Wrangler

Astro on Cloudflare

Best for

Small SaaS backends, internal tools, realtime apps

Anything where you want full control

Content sites, blogs, docs

Bindings

Inferred from imports

Hand-written wrangler.jsonc

Hand-written, or Void in framework mode

Migrations

Generated, applied on deploy, restore point saved

wrangler d1 migrations apply

Same as Workers, or Void

Auth

Built in (native only)

Bring your own

Bring your own (Better Auth has an integration)

Realtime

SSE, void/live, WebSockets, Durable State

Write the Durable Objects yourself

Write them yourself

Maturity

1.0 in October 2026, several releases a week

Years

Years

Docs

Track main, some mismatches

Cloudflare's own

Astro's plus Cloudflare's

Node

24.22+ or 26.12+

Whatever Wrangler needs

Whatever Astro needs

My decision rule

Content first, mostly pages? Astro. Add Void in framework mode if you want the typed database and migrations.

App first, with a database, auth or live updates, and you own the code end to end? Void. Pin the version and budget time for upgrades.

Anything you'd hate to rewrite in a year, or a team that can't absorb churn? Plain Workers. The extra config is the price of a stack that changes on your schedule.

When I'm torn, I ask one thing: will I still be here to read the release notes every week? If yes, Void saves real work. If not, Wrangler.

Production readiness checklist for Void

Before I'd put a Void app in front of users:

  • [ ] Node 24.22+ or 26.12+ locally and in CI (set node-version explicitly in the deploy workflow)
  • [ ] Void pinned exactly (npm install -D -E void@1.12.2), and upgrades read against the release notes
  • [ ] No reliance on features the docs describe but your version lacks (Workflows, as of 1.12.2)
  • [ ] void.config.ts and void.lock.json committed
  • [ ] Every schema change backward compatible with the previous release, because rollback doesn't undo migrations
  • [ ] The restore point line from each deploy saved somewhere
  • [ ] Production secrets set with void secret put or void secret sync, and npx void env check passing
  • [ ] Queue consumers record their own failures (there's no dead-letter queue)
  • [ ] void/live used only where at-most-once, 256 subscribers per topic and drops on deploy are acceptable
  • [ ] Caught errors also go to console.error(), since void project logs on Cloudflare is a live tail with no history
  • [ ] CPU limit set in void.config.ts, and Workers Paid if you need more than 10 ms
  • [ ] A rollback drill done once, on purpose, before you need it

The self-hosted platform

A Void platform is a deploy service you install into your own Cloudflare account so a team can ship without sharing account credentials, with retained logs and deploy history. It needs Workers for Platforms (a separate paid plan), R2, Analytics Engine, a hosted PostgreSQL database you provide, and a login provider. For one person shipping their own apps, I wouldn't bother. For a team that wants one deploy target with guardrails, it's worth a void platform install --plan to see what it would create.

Where I landed

This site stays on Astro. The team board from Part 2 stays on Void, pinned, and I'll keep this guide current as Void moves. Build something small with it first, and decide from there.

About Roger

I'm Roger Stringer. I build things, break them, and write up what I learned so you don't have to learn it the hard way. These Field Guides come straight out of that work.

Working on something bigger? I take on a handful of fractional CTO engagements, helping founders and teams set technical direction, build AI-powered workflows, and actually ship the hard parts. If you're wrestling with the kind of problem this guide covers and want someone in your corner who's done it before, that's exactly what I help with. Drop me a line.

And if a guide helped, got something wrong, or you just want to compare notes, I'd love to hear from you:

New guides go up as I hit problems worth documenting. Follow along wherever suits you.

Do you like my content?

Sponsor Me On Github

Keep reading