---
title: Write hooks
description: Run your code after a write commits, with the rows it wrote
icon: webhook
---

`on()` is the official write-hook extension. You name a model and what
happened to its rows (`create`, `update`, `delete`), and VibORM calls your
function after the write commits, with those rows as the write left them.

```ts
import { on } from "viborm/on";

const db = base.$extends(on({
  user: {
    update: (rows, { certainty }) => syncToMyOtherDatabase(rows),
    delete: (rows) => removeFromSearchIndex(rows.map((row) => row.id)),
  },
}));

await db.user.update({ where: { id: "u1" }, data: { name: "Ada" } });
// committed, then syncToMyOtherDatabase([{ id: "u1", name: "Ada", … }])
```

The extension lives in its own entry point, so an application that does not
import it pays nothing for it. A write no hook concerns runs exactly as it
does without the extension: the same statements, no extra `RETURNING`
column, no extra read.

Declare the hooks inside `$extends(on({...}))`: the receiving client's schema
then types the model names, the hook names and each hook's rows, and a
misspelt model, hook or field is an editor error.

## What a hook receives

```ts no-check
(rows, event) => unknown
```

- `rows`: the rows the write changed, as they are after the write. For a
  delete, as they were before it. A row has every scalar field a plain
  `findMany` returns (see [below](#the-rows-a-hook-receives)), whatever the
  call selected.
- `event.model` and `event.operation`: the call that wrote them
  (`"user"`, `"updateMany"`; `"upsert"` for either arm of an upsert). For
  rows a nested write wrote, the root call's: a `user.update` hook called by
  `post.update({ data: { author: { update: {…} } } })` receives
  `model: "post"`, `operation: "update"`.
- `event.args`: the call's arguments, after the extensions' first moments
  (`call` patches) and default omission.
- `event.certainty`: `"committed"`, or `"may-have-committed"` when the
  provider could not confirm the commit (a connection lost while committing):
  the write may be durable or not.

A hook is called once per call, with all of the rows of its model that call
wrote, its own and its nested writes' alike. A write that changes no row (an
`updateMany` matching nothing) calls no hook.

## Which hook a write calls

| Call | Hook | `rows` |
|---|---|---|
| `create` | `create` | the created row |
| `createMany` | `create` | the created rows; with `skipDuplicates`, only those inserted |
| `update` | `update` | the row after the update |
| `updateMany` | `update` | every row it matched, after the update |
| `upsert` | `create` when it inserted, `update` when it updated (an empty `update: {}` writes nothing and calls no hook) | the row after the write |
| `delete` | `delete` | the row before the delete |
| `deleteMany` | `delete` | every row it deleted, before the delete |
| `delete`, `deleteMany` of a model [soft delete](/docs/extensions/soft-delete) manages | `update` | the rows after the tombstone is written; with `mode: "hard"`, `delete` and the rows before |
| `restore`, `restoreMany` (soft delete) | `update` | the rows after the restore |
| `connect` or `disconnect` of a relation whose foreign key the called row holds | the called row's own hook (`update`, or `create`) | that row, with its new foreign key (a polymorphic relation's columns are not in the row, see [below](#the-rows-a-hook-receives)) |

Nested writes call the hooks of the model they write, with the same mapping:

| Nested write | Hook of the nested model | `rows` |
|---|---|---|
| `create`, `createMany` | `create` | the created rows |
| `update`, `updateMany` | `update` | the rows after the write |
| `upsert`, `connectOrCreate` | `create` when it created, `update` when it updated (an `upsert` whose `update` writes nothing calls none; a `connectOrCreate` that connects a row whose foreign key it moves calls `update`) | the row after the write |
| `connect` (the nested row holds the foreign key) | `update` | the row with its new foreign key |
| `disconnect`, `set` (rows whose foreign key is cleared) | `update` | each row with the foreign key cleared |
| `delete`, `deleteMany` | `delete` | the rows before the delete |
| `delete`, `deleteMany` of a model soft delete manages | `update` | the rows after the tombstone is written |

A nested `connect` or `disconnect` whose foreign key the parent row holds
changes the parent row, which is the call's own row or a nested one: its hook
says so.

What never calls a hook:

- **Many-to-many links.** A link row of an implicit many-to-many relation is
  not a row of either model. Declare the join table as a model with two
  to-one relations when you need hooks on links: its rows are then created and
  deleted like any other.
- **What the database does on its own**: `ON DELETE CASCADE`,
  `ON DELETE SET NULL`, `ON UPDATE CASCADE`, triggers and generated columns
  changed by them. VibORM never sees those rows.
- **Raw SQL** (`$executeRaw`, `$queryRaw`).

## When a hook runs

**After the commit, and only then.**

- A direct write calls its hooks once it has committed, and its promise
  resolves after them.
- Inside `$transaction(async (tx) => …)`, a write's hooks wait for the
  outermost commit. A savepoint (`tx.$transaction(…)`) that rolls back drops
  the hooks of its writes; one that succeeds hands them to its parent. A
  transaction that rolls back calls none. The hooks run before the
  `$transaction` promise resolves, in the order the writes ran.
- In `$transaction([...])`, every member's hooks run after the commit, in
  member order.
- A write that fails calls no hook, even one that may have written before it
  failed.

**A hook cannot change or cancel the write.** It runs after the commit; the
rows and the `event.args` it receives are its own copies (neither the caller
nor the hook changes what the other holds), and what it returns is only
awaited.

**If the process dies after the commit, the hook is lost.** There is no
outbox: a hook that must run for every committed write belongs in the same
transaction as the write (an outbox table you write yourself, or a database
trigger), not in a hook.

## Waiting for a hook, or not

VibORM awaits what a hook returns, then resolves the write. You decide what
the write waits for:

```ts
on({
  user: {
    // The write resolves after the sync (a failure goes to `onError`).
    update: (rows) => syncToMyOtherDatabase(rows),
    // The write resolves at once; the platform keeps the work alive.
    create: (rows) => {
      ctx.waitUntil(sendWelcomeEmails(rows));
    },
  },
});
```

VibORM takes no `waitUntil` option: return the promise to wait for it, or
hand it to your platform yourself.

## When a hook fails

**A failing hook never fails its write.** The write committed, so its promise
resolves with its value, inside a transaction and in `$transaction([...])`
too. Code that retries a failed write never writes it twice because of a
hook. The hook's failure goes to `onError`, the second argument of `on()`:

```ts
const db = base.$extends(
  on(
    { user: { update: (rows) => syncToMyOtherDatabase(rows) } },
    {
      onError: (error, event) => {
        error.meta.commitCertainty; // "committed": the row IS updated
        error.cause; // what your hook threw
        return reportToMyErrorTracker(error, event.args);
      },
    }
  )
);
```

- `error` is a `QueryError` naming the hook (`Extension "viborm.on" hook
  user.update failed after the write committed; the write is not undone.`),
  with `meta.method: "on"`, the call's `model` and `operation`, and
  `commitCertainty`; `cause` is the error the hook threw. `event` is the
  hook's own event.
- VibORM awaits what `onError` returns before the write resolves, like a
  hook's own promise.
- Without `onError`, the failure goes to `console.error`, and so does an
  `onError` that throws. Neither ever fails the write.
- Every hook runs: in a transaction or an array, one hook failing does not
  keep the next from running; each failure is reported on its own.
- The [cache](/docs/extensions/cache)'s own invalidation failure is not a
  hook's: it still fails the write, as it does without `on()`.
- An [`around`](/docs/extensions/create#the-second-moment-around)
  that throws after its write committed does not lose the hook: it has
  already run.

## Request-scoped values (Cloudflare Workers)

A hook often needs something that only exists during a request, such as the
Worker's `ctx` for `ctx.waitUntil()`. Apply `on()` **per request**, inside a
function that takes the client, so the client's schema still types the hooks
and the hooks close over the request's values:

```ts
import { createClient } from "viborm/d1";
import { on } from "viborm/on";

// D1's binding exists only in the request's env: build the client there.
const database = (env: Env) => createClient({ database: env.DB, schema });
type Database = ReturnType<typeof database>;

// `db.$extends(on(...))` inside: rows, models and hooks are typed from `db`.
const withHooks = (db: Database, ctx: ExecutionContext, env: Env) =>
  db.$extends(
    on({
      user: {
        update: (rows) => {
          ctx.waitUntil(env.SYNC_QUEUE.sendBatch(rows.map((body) => ({ body }))));
        },
      },
    })
  );

export default {
  async fetch(request, env, ctx) {
    const db = withHooks(database(env), ctx, env);
    await db.user.update({ where: { id: "u1" }, data: { name: "Ada" } });
    return new Response("ok");
  },
} satisfies ExportedHandler<Env>;
```

The client `$extends` returns shares its base client's schema, driver and
connection; deriving it per request costs one `$extends`. Nothing is shared
between requests: two concurrent requests each hold their own `ctx`.

A declaration made apart from any client (`const hooks = (ctx) => on({...})`)
also works, but nothing types it: any model name and plain records. Keep the
`$extends(on(...))` call where the client is in scope, as above, to keep the
editor's checks.

Why not the other two places a request value could come from:

- **A bound argument** (like the permissions entry's `$as`) is a value of the
  calls a client makes, handed to the parts of the extension that declares it.
  A hook runs after the commit, outside every part, and a `waitUntil` is not a
  value a call should carry.
- **A hook argument** would make VibORM carry your platform's request object,
  and every runtime names it differently. A closure carries exactly what you
  give it.

When the base client already binds per request (permissions' `$as`), apply
`on()` to the bound client: `withHooks(base.$as(actor), ctx, env)`.

## The rows a hook receives

A row has every scalar field of the model a plain `findMany` returns from the
schema alone (`InferDatabase<typeof schema>["user"]["Row"]`, also exported as
`OnRow<typeof user>`), decoded as a read decodes it (`Date`, `Decimal`,
`bigint`, JSON):

- **`defaultOmit()` does not hide a field from a hook.** A default omit is
  presentation for callers; the hook receives the row as the database holds
  it. A field the schema itself omits (`.omit()`) is not in the row.
- **Computed `result` fields are not attached.** Compute what you need from
  the row.
- **The call's `select`, `include` and `omit` do not change it.** The caller
  still receives exactly the projection it asked for.
- Under [permissions](/docs/extensions/permissions), a field `reads` gates is
  in a row only where the call may read it, as in a default projection; its
  type in a hook's row is optional.
- **A polymorphic relation's columns are not in the row**, as they are not in
  a default projection: a hook cannot see which variant a row now points to.
  Read the relation itself when you need it.

## What a hook costs

Nothing when no hook concerns the write. A write a hook concerns returns whole
rows instead of the caller's projection, through the statements it already
sends wherever the database can (`RETURNING`). Measured statements per call
(provider batches on D1 and Neon HTTP), without a hook → with one; a
transaction adds its `BEGIN` and `COMMIT`:

| Call | PostgreSQL (incl. Neon HTTP) | SQLite, libSQL | D1 | MySQL |
|---|---|---|---|---|
| `create`, `update`, `delete` | 1 → 1 | 1 → 1 | 1 → 1 | unchanged (2–4 in a transaction) |
| `createMany` of N rows | 1 → 1 | 1 → 1 | 1 → 1 | 1 → 2 (one INSERT, one read) in a transaction |
| `updateMany` | 1 → 1 | 1 → 1 | 1 → 1 | 1 → 3 (lock the keys, write, read) in a transaction |
| `deleteMany` | 1 → 1 | 1 → 1 | 1 → 1 | 1 → 2 (lock and read, delete) in a transaction |
| `upsert` | 1 → 1 | 1 → 2 in a transaction | 1 → 2 in one batch | unchanged (3–5 in a transaction) |

- Where a write already returns its row, a hook only widens what it returns
  to every column: no extra statement.
- A bulk write a hook concerns returns its rows (`RETURNING`). MySQL has no
  `RETURNING`, so there it reads them in the same transaction, the way a bulk
  write with a `select` does there: a `createMany` inserts its rows in one
  statement and reads them back by their keys (row by row instead when a key
  is generated by the database, such as an auto-increment, or with
  `skipDuplicates`, to learn which rows it inserted); a `deleteMany` locks and
  reads its rows in one `SELECT … FOR UPDATE`; an `updateMany` locks their
  keys, writes them and reads them back.
- **A nested write** a hook concerns reads back each row it writes, by key,
  in the same transaction (in the same batch on D1 and Neon HTTP: no extra
  round trip): one statement more per nested `create`, `update`, `upsert`,
  `connect`, `disconnect` and `delete`. A nested `updateMany` or `deleteMany`
  returns its rows from its own statement (`RETURNING`, no extra statement);
  on MySQL it locates its rows and writes and reads each one. A nested write
  of a model no hook names reads nothing.
- An `upsert` reports which arm it took and stays one atomic
  `INSERT … ON CONFLICT`. On PostgreSQL its `RETURNING` says so (`xmax = 0`).
  SQLite's statement cannot, so a probe of the key goes just before it, in the
  same transaction (in the same batch on D1). On a PostgreSQL **partitioned or
  foreign table**, PostgreSQL cannot return `xmax`: an upsert a hook concerns
  fails there, so do not hook upserts of such a table.

## Composing

Apply `on()` before or after any other extension. It sees the writes of the whole chain, including the update a soft
delete makes of a delete and the rows a permission lets a call write (a row the
call may not write is not written, so it calls no hook). Every other
extension's `around` sees the call's own value, exactly what the caller
asked for, never the whole rows the hook receives.

One client can carry several `on()`: each call of `on()` makes an extension of
its own name, counted in the program (the first `on()` called is `viborm.on`,
the next `viborm.on.2`, …), and each runs its own hooks, in the order they
were applied. A hook's failure says `viborm.on` whichever `on()` holds it. Applying the same `on()` value twice to one
client is refused, as any extension applied twice. A hook name other than
`create`, `update` and `delete`, a hook that is no function, and an `onError`
that is no function are refused when `on()` is called; a model the schema
lacks is refused when the extension is applied. Each is a
`ClientInitializationError`. To name a hooked client's type, use `typeof` on
the client `$extends(on(...))` returns.

`on()` is written with the public parts: a `call` on
[`target(writes)`](/docs/extensions/create#which-calls-target) that
[`watch`](/docs/extensions/create#receive-the-rows-a-write-wrote-watch)es the
rows a write wrote and is
[`settled`](/docs/extensions/create#act-after-the-commit-settled) after its
commit. The selector of a call part is `target`, so `on` names only this
extension.

## Not covered

- Hooks before a write, or hooks that change it: use a
  [`call`](/docs/extensions/create#call-a-function-on-a-call) or
  [`defaults`](/docs/extensions/create#default-data-create-update).
- Delivery that survives a crash: write an outbox row in the transaction.
