---
title: Callbacks
description: "Run your code at points in a record’s lifecycle, such as before it’s validated or after it’s saved."
seo:
  description: "Run code at points in an Active Record record’s lifecycle: before validation, around a save, after commit, and abort() to stop a save or destroy."
---

## At a glance

| To                                         | Write                                                      |
| ------------------------------------------ | ---------------------------------------------------------- |
| run code before a record is validated      | `this.beforeValidation((order) => { … })`                  |
| run code only when a record is created     | `beforeCreate`, or `beforeValidation(…, { on: "create" })` |
| run code on both sides of a write          | `this.aroundSave(async (order, next) => { await next() })` |
| send an email once a record is created     | `this.afterCreateCommit(async (user) => { … })`            |
| run code after `touch()`                   | `this.afterTouch(…)`                                       |
| run code when the database refuses a write | `this.afterRollback(…)`                                    |
| fill in a new record’s defaults            | `this.afterInitialize(…)`                                  |
| stop a save or destroy                     | `throw abort("reason")` in a before-callback               |

## The Models

The examples use these Models, whose attributes come from their tables through the schema `active-record schema` generates. Each registers its callbacks in its `static {}` block, and `mail.ts` and `cache.ts` stand in for the app’s own services:

```ts order.ts
import { abort } from "@forestfuture/active-record";
import { sendShippedEmail } from "../mail";
import { ApplicationRecord } from "./application-record";

export class Order extends ApplicationRecord {
  static {
    this.beforeValidation((order) => {
      order.email = order.email.trim().toLowerCase();
    });
    this.beforeValidation(
      (order) => {
        order.placedAt = new Date();
      },
      { on: "create" },
    );
    this.beforeSave((order) => {
      if (order.isSuspended) throw abort("Orders can't change while suspended");
    });
    this.aroundSave(async (order, next) => {
      const started = Date.now();
      await next();
      console.log(`Saved order ${order.number} in ${Date.now() - started} ms`);
    });
    this.afterSave(async (order) => {
      if (order.hasSavedChangeTo("status", { to: "shipped" })) {
        await sendShippedEmail(order.email);
      }
    });
    this.afterRollback((order) => {
      console.log(`Order ${order.number} wasn't saved`);
    });
  }
}
```

```ts user.ts
import { sendWelcomeEmail } from "../mail";
import { ApplicationRecord } from "./application-record";

export class User extends ApplicationRecord {
  static {
    this.afterCreateCommit(async (user) => {
      await sendWelcomeEmail(user.email);
    });
  }
}
```

```ts article.ts
import { purgeCachedPage } from "../cache";
import { ApplicationRecord } from "./application-record";

export class Article extends ApplicationRecord {
  static {
    this.afterTouch(async (article) => {
      await purgeCachedPage(`/articles/${article.id}`);
    });
  }
}
```

```ts invoice.ts
import { ApplicationRecord } from "./application-record";

export class Invoice extends ApplicationRecord {
  static {
    this.afterInitialize((invoice) => {
      if (invoice.isNewRecord()) invoice.currency ??= invoice.country === "GB" ? "GBP" : "USD";
    });
    this.afterFind((invoice) => {
      // A record loaded with select() may leave totalCents out.
      if (invoice.hasAttribute("totalCents") && invoice.totalCents > 1_000_000) {
        console.log(`Large invoice ${invoice.id} loaded`);
      }
    });
  }
}
```

```ts mail.ts
// The app's emails. Here they're logged, as a test's mailer would.
export async function sendWelcomeEmail(email: string): Promise<void> {
  console.log(`Welcome email to ${email}`);
}

export async function sendShippedEmail(email: string): Promise<void> {
  console.log(`Shipped email to ${email}`);
}
```

```ts cache.ts
// The app's page cache. Here a purge is logged.
export async function purgeCachedPage(path: string): Promise<void> {
  console.log(`Purged ${path}`);
}
```

```ts schema.ts
// Generated by `active-record schema` from migrations/ — don't edit.
// schema: 141262a87f5f

import { defineSchema, type TableAttributes } from "@forestfuture/active-record";
import { d1 } from "@forestfuture/active-record/d1";

/** articles — last changed by 0001_create_tables.sql */
export const articles = {
  id: { type: "string", null: false, generateId: true },
  title: { type: "string", null: false },
  updatedAt: "datetime",
} as const;

/** invoices — last changed by 0001_create_tables.sql */
export const invoices = {
  id: { type: "string", null: false, generateId: true },
  country: { type: "string", null: false },
  currency: "string",
  totalCents: { type: "integer", null: false, default: () => 0 },
} as const;

/** orders — last changed by 0001_create_tables.sql */
export const orders = {
  id: { type: "string", null: false, generateId: true },
  number: { type: "string", null: false },
  status: { type: "string", null: false, default: () => "pending" },
  email: { type: "string", null: false },
  totalCents: { type: "integer", null: false },
  isSuspended: { type: "boolean", null: false, default: () => false },
  placedAt: "datetime",
} as const;

/** users — last changed by 0001_create_tables.sql */
export const users = {
  id: { type: "string", null: false, generateId: true },
  email: { type: "string", null: false },
} as const;

/** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */
export const schema = defineSchema({
  adapter: d1({ binding: "DB" }),
  tables: {
    articles: { attributes: articles, primaryKey: "id" },
    invoices: { attributes: invoices, primaryKey: "id" },
    orders: { attributes: orders, primaryKey: "id" },
    users: { attributes: users, primaryKey: "id" },
  },
  models: { Article: "articles", Invoice: "invoices", Order: "orders", User: "users" },
});

declare module "../models/article" {
  interface Article extends TableAttributes<typeof articles, (typeof Article)["attributes"]> {}
}

declare module "../models/invoice" {
  interface Invoice extends TableAttributes<typeof invoices, (typeof Invoice)["attributes"]> {}
}

declare module "../models/order" {
  interface Order extends TableAttributes<typeof orders, (typeof Order)["attributes"]> {}
}

declare module "../models/user" {
  interface User extends TableAttributes<typeof users, (typeof User)["attributes"]> {}
}
```

```sql D1
CREATE TABLE orders (
  id TEXT PRIMARY KEY NOT NULL,
  number TEXT NOT NULL,
  status TEXT NOT NULL DEFAULT 'pending',
  email TEXT NOT NULL,
  total_cents INTEGER NOT NULL,
  is_suspended BOOLEAN NOT NULL DEFAULT FALSE,
  placed_at DATETIME
);
CREATE UNIQUE INDEX index_orders_on_number ON orders (number);
CREATE TABLE users (
  id TEXT PRIMARY KEY NOT NULL,
  email TEXT NOT NULL
);
CREATE TABLE articles (
  id TEXT PRIMARY KEY NOT NULL,
  title TEXT NOT NULL,
  updated_at DATETIME
);
CREATE TABLE invoices (
  id TEXT PRIMARY KEY NOT NULL,
  country TEXT NOT NULL,
  currency TEXT,
  total_cents INTEGER NOT NULL DEFAULT 0
);
```

```sql Postgres
CREATE TABLE orders (
  id UUID PRIMARY KEY,
  number TEXT NOT NULL,
  status TEXT NOT NULL DEFAULT 'pending',
  email TEXT NOT NULL,
  total_cents INTEGER NOT NULL,
  is_suspended BOOLEAN NOT NULL DEFAULT FALSE,
  placed_at TIMESTAMPTZ
);
CREATE UNIQUE INDEX index_orders_on_number ON orders (number);
CREATE TABLE users (
  id UUID PRIMARY KEY,
  email TEXT NOT NULL
);
CREATE TABLE articles (
  id UUID PRIMARY KEY,
  title TEXT NOT NULL,
  updated_at TIMESTAMPTZ
);
CREATE TABLE invoices (
  id UUID PRIMARY KEY,
  country TEXT NOT NULL,
  currency TEXT,
  total_cents INTEGER NOT NULL DEFAULT 0
);
```

## Registering callbacks

Register callbacks in a Model’s `static {}` block, as `Order` does, and they run as the record is saved:

```ts
import { Order } from "./models/order";

const order = await Order.create({
  number: "1001",
  email: " Jane@Example.com ",
  totalCents: 2500,
});
console.log(order.email); // "jane@example.com", from the first beforeValidation
console.log(order.placedAt); // now, from the beforeValidation that runs on create

await order.update({ status: "shipped" }); // afterSave sends the shipped email
```

- Each callback receives the record, and may be async, except the [callbacks for a record built or loaded](#running-code-when-a-record-is-built-or-loaded).
- Callbacks of one kind run in the order declared. A subclass runs its parent’s callbacks, then its own.
- Pass `on` to `beforeValidation` or `afterValidation` to run it only in some [validation contexts](/validations#validating-only-when-creating-or-updating), as `Order`’s second `beforeValidation` does.

:::note
Once a Model has been used, registering another callback throws `InvalidModel`, so request code can’t add one that leaks into later requests.
:::

## Callback order

| Order          | Callback             | Runs                                                     | `abort()`                         |
| -------------- | -------------------- | -------------------------------------------------------- | --------------------------------- |
| **Saving**     |                      |                                                          |                                   |
| 1              | `beforeValidation`   | Before the validators, on every save, and on `isValid()` | Stops the save                    |
| 2              | `afterValidation`    | After the validators                                     | Stops the save                    |
| 3              | `beforeSave`         | Before every write, new or persisted                     | Stops the save                    |
| 4              | `aroundSave`         | Its first part, before `next()`                          | Stops the save                    |
| 5              | `beforeCreate`       | Before inserting a new record                            | Stops the save                    |
| 5              | `beforeUpdate`       | Before updating a persisted record                       | Stops the save                    |
| 6              | `aroundCreate`       | Its first part, before `next()`                          | Stops the save                    |
| 6              | `aroundUpdate`       | Its first part, before `next()`                          | Stops the save                    |
|                | _The write_          | Skipped when a persisted record has no changes           |                                   |
| 7              | `aroundCreate`       | Its last part, once `next()` resolves                    | Too late: `AbortAfterPersistence` |
| 7              | `aroundUpdate`       | Its last part, once `next()` resolves                    | Too late: `AbortAfterPersistence` |
| 8              | `afterCreate`        | After inserting a new record                             | Too late: `AbortAfterPersistence` |
| 8              | `afterUpdate`        | After updating a persisted record                        | Too late: `AbortAfterPersistence` |
| 9              | `aroundSave`         | Its last part, once `next()` resolves                    | Too late: `AbortAfterPersistence` |
| 10             | `afterSave`          | After every successful save                              | Too late: `AbortAfterPersistence` |
| 11             | `afterCommit`        | Last, after every after-callback                         | Too late: `AbortAfterPersistence` |
| 11             | `afterCreateCommit`  | Last, after inserting a new record                       | Too late: `AbortAfterPersistence` |
| 11             | `afterUpdateCommit`  | Last, after updating a persisted record                  | Too late: `AbortAfterPersistence` |
| 11             | `afterSaveCommit`    | Last, after every successful save                        | Too late: `AbortAfterPersistence` |
| **Destroying** |                      |                                                          |                                   |
| 1              | `beforeDestroy`      | Before the `dependent` strategies and the DELETE         | Stops the destroy                 |
| 2              | `aroundDestroy`      | Its first part, before `next()`                          | Stops the destroy                 |
|                | _The delete_         | With the dependents, in one batch                        |                                   |
| 3              | `aroundDestroy`      | Its last part, once `next()` resolves                    | Too late: `AbortAfterPersistence` |
| 4              | `afterDestroy`       | After the record is destroyed                            | Too late: `AbortAfterPersistence` |
| 5              | `afterCommit`        | Last, after every after-callback                         | Too late: `AbortAfterPersistence` |
| 5              | `afterDestroyCommit` | Last, after the record is destroyed                      | Too late: `AbortAfterPersistence` |
| **Touching**   |                      |                                                          |                                   |
|                | _The write_          | `updatedAt`, and any attributes named                    |                                   |
| 1              | `afterTouch`         | After `touch()` writes the record’s timestamps           | Too late: `AbortAfterPersistence` |
| 2              | `afterCommit`        | Last, when `touch()` wrote a row                         | Too late: `AbortAfterPersistence` |
| 2              | `afterUpdateCommit`  | Last, when `touch()` wrote a row                         | Too late: `AbortAfterPersistence` |
| 2              | `afterSaveCommit`    | Last, when `touch()` wrote a row                         | Too late: `AbortAfterPersistence` |
| **Refused**    |                      |                                                          |                                   |
| 1              | `afterRollback`      | When the database refuses the save or destroy            | Nothing to stop                   |
| **Loading**    |                      |                                                          |                                   |
| 1              | `afterFind`          | After a record is loaded                                 | Nothing to stop                   |
| 2              | `afterInitialize`    | After a record is loaded, or built                       | Nothing to stop                   |

A save runs either the create pair or the update pair, never both.

- **After-callbacks** run after every successful save, even one with no changes to write.
- **A before-callback that changes an attribute** makes the record dirty, and the change is written.
- **An after-callback that changes an attribute** leaves the record dirty. Nothing is written again.

:::warning[Nothing is rolled back]
The database has kept a save’s writes before any after-callback runs. An error thrown by an after-callback or a commit callback reaches the caller, but the record stays saved. The callbacks after it don’t run. In a batch, that includes the other records’ callbacks.
:::

## Wrapping a save or destroy

An around callback runs code on both sides of a write, as `Order`’s `aroundSave` does. Call `next()` to run the rest of the save, and await it.

- **`aroundSave`** runs after `beforeSave`. Its `next()` runs `beforeCreate` or `beforeUpdate`, the write, and `afterCreate` or `afterUpdate`. `afterSave` runs once the callback finishes.
- **`aroundCreate`**, **`aroundUpdate`**, and **`aroundDestroy`** wrap only the write, between the matching before- and after-callbacks.
- **Several around callbacks of one kind** nest. The first one declared is the outermost.

`next()` returns a promise with no value. It resolves once the database has kept the write. A save sends its writes together, so in a [batch](/batches#batching-records), every record’s first part runs before the batch is written. Then each record’s last part runs in turn.

### Stopping a wrapped write

- **Not calling `next()`** stops the save, as `abort()` does. `save()` resolves to `false`, and nothing is written.
- **An `abort()` before `next()`** stops the save. After `next()`, the write has happened, so `abort()` throws `AbortAfterPersistence`.
- **When the database refuses the write**, `afterRollback` runs, then `next()` rejects with the database’s error. The save throws it even if you catch it.
- **When the save ends without sending the write**, `next()` rejects with the error the save ends with. That happens when another record in the save or batch is refused before the write is sent.
- **When an earlier record’s after-callback throws**, the write is kept. This record’s after-callbacks are skipped, and `next()` rejects with that error.

To release something you hold during the write, put `await next()` in a `try` block, and release it in `finally`.

## Running code after the commit

Register a commit callback, as `User` does, to run code once everything is written:

```ts
import { User } from "./models/user";

await User.create({ email: "sam@example.com" }); // then afterCreateCommit sends the welcome email
```

Commit callbacks run last, after every after-callback of the save. In a [batch](/batches#batching-records), they wait for every record’s after-callbacks.

- **`afterCommit`** runs after a create, an update, or a destroy.
- **`afterCreateCommit`**, **`afterUpdateCommit`**, and **`afterDestroyCommit`** run after one kind of write. **`afterSaveCommit`** runs after a create or an update.
- **Commit callbacks of every kind** run in the order you declared them.

:::note
Destroying a record that was never saved runs no commit callback, since there was no row to delete.
:::

## Running code after a touch

`afterTouch` runs after [`touch()`](/persistence#touching-a-record) writes a record’s timestamps, as `Article`’s does:

```ts
import { Article } from "./models/article";

const article = await Article.findByOrThrow({ title: "Hello" });
await article.touch(); // sets updatedAt, then afterTouch purges the cached page
```

- **No validation or save callback runs** for a touch.
- **The commit callbacks for an update** run after `afterTouch`: `afterCommit`, `afterUpdateCommit`, and `afterSaveCommit`. When the row is gone, only `afterTouch` runs.
- **`savedChanges()`** holds only the touched attributes, so `hasSavedChangeTo("email")` is `false` in a touch’s callbacks.
- **A refused touch** runs `afterRollback`, and the record stays as it was.

A `belongsTo` declared with [`touch`](/touching#touching-the-record-it-belongs-to) touches its record the same way. Saving a comment can run its article’s `afterTouch` and commit callbacks.

`touchAll` and the counters’ `touch` option run no callbacks.

:::warning[A touch runs the update commit callbacks]
A `touch()` that writes a row runs `afterUpdateCommit`. To send an email only when a record is saved, register it with `afterUpdate` instead. It runs once the database has kept the save.
:::

## Handling a refused write

`afterRollback` runs when the database refuses a record’s save or destroy, as `Order`’s does for a number that’s taken:

```ts
import { Order } from "./models/order";

const order = Order.build({ number: "1001", email: "sam@example.com", totalCents: 900 });
await order.save(); // throws RecordNotUnique, once afterRollback has logged "Order 1001 wasn't saved"
```

- **A constraint error** refuses the record’s write, and the save then throws the [constraint error](/errors#constraint-errors).
- **In a batch**, one refused write refuses them all, so `afterRollback` runs for every record in it.
- **A failed validation or an `abort()`** sends nothing, so `afterRollback` doesn’t run.

The record keeps its unsaved state, and no after-callback or commit callback runs for it.

:::note
An error thrown by an `afterRollback` reaches the caller in place of the constraint error, which becomes its `cause`. The `afterRollback` callbacks after it don’t run.
:::

## Running code when a record is built or loaded

`afterInitialize` runs for every record you build and every record you load, as `Invoice`’s fills in a new invoice’s currency. `afterFind` runs for every record you load, just before `afterInitialize`:

```ts
import { Invoice } from "./models/invoice";

const invoice = Invoice.build({ country: "GB" });
console.log(invoice.currency); // "GBP", from afterInitialize
```

- **`build` and `create`** run `afterInitialize` after their `init` function, so it sees what `init` set. Building through a `hasMany` or `hasOne` runs it once the record points at its owner. Building through a `through` association runs the join record’s `afterInitialize` once it points at the record.
- **Every load** runs `afterFind`, then `afterInitialize`: a query, an association read, a preload, and `reload()`. Preloaded associations aren’t attached yet when they run.
- **Saving a record** runs neither, and neither does `new Invoice()`.

Both callbacks run synchronously, since `build` can’t wait for them. An `async` one is a type error. An error thrown by either reaches the caller, and the query returns no records.

### Handling partial records

A record loaded with [`select`](/querying#selecting-attributes) runs both callbacks too, and reading an attribute it left out throws `MissingAttribute`. Check with `hasAttribute` first, as `Invoice`’s `afterFind` does:

```ts
import { Invoice } from "./models/invoice";

const invoices = await Invoice.select("id", "country").toArray(); // afterFind skips the total
const large = await Invoice.where({ country: "US" }).toArray(); // afterFind logs the large one
```

## Stopping a save

Throw `abort(reason)` from a before-callback to stop a save or destroy, as `Order`’s `beforeSave` does for a suspended order:

```ts
import { Order } from "./models/order";

const order = await Order.findByOrThrow({ number: "1002" }); // a suspended order
order.totalCents = 0;
await order.save(); // false, and nothing is written
console.log(order.abortReason); // "Orders can't change while suspended"
```

- **`save()`** resolves to `false` and writes nothing. The record keeps its changes, and `record.abortReason` holds the reason.
- **`saveOrThrow()`** throws `RecordNotSaved` with the reason.
- **`destroy()`** resolves to `false`, and **`destroyOrThrow()`** throws `RecordNotDestroyed`.

Only `abort()` stops a save. Returning `false` does nothing, and any other error reaches the caller as it is.

:::note
In an after-callback, the write has already happened, so `abort()` throws `AbortAfterPersistence`, naming the callback.
:::

> **Compared with Rails**
>
> `after_commit` and its `on:` forms are `afterCommit`, `afterCreateCommit`, `afterUpdateCommit`, `afterSaveCommit`, and `afterDestroyCommit`, run in the order declared, as Rails 7.1 runs them. In Rails, `after_save` runs before the save’s transaction commits. Here, the database has already kept the write before any after-callback runs, so every after-callback is already “after commit”. An error in `afterSave` rolls a Rails save back; here the record stays saved, and its commit callbacks don’t run.
>
> `after_touch` is `afterTouch`. As in Rails, `touch` runs the commit callbacks too.
>
> `after_rollback` is `afterRollback`. Rails also runs it for a save that fails inside a transaction. Here it runs only when the database refuses a write, since validation and the before-callbacks run before anything is sent.
>
> `around_save`, `around_create`, `around_update`, and `around_destroy` are `aroundSave`, `aroundCreate`, `aroundUpdate`, and `aroundDestroy`, and `yield` is `await next()`. Rails wraps each record’s own SQL in its transaction. Here, `next()` waits for the whole save’s batch. A Rails `around_save` can rescue the database’s error and carry on; here the save still throws it. Rails saves a `has_many`’s autosaved records inside the owner’s `around_save`. Here, the owner’s `aroundSave` finishes before their after-callbacks run. When an inner `around_save` doesn’t `yield`, Rails resumes the outer one after its `yield`. Here, the outer one’s `next()` rejects, and nothing is saved.
>
> `after_initialize` and `after_find` are `afterInitialize` and `afterFind`, and run in the same order. Here they can’t be async. `new Invoice()` doesn’t run `afterInitialize`, where Rails’ `new` does: build records through the Model instead, with `Invoice.build()`. `reload()` runs both on the record itself, where Rails runs them on a fresh copy and takes its attributes. `has_attribute?` is `hasAttribute`.
>
> Rails’ `if:` and `unless:` options for callbacks aren’t needed: write the condition inside the callback.
