Lifecycle Hooks
Intercept CRUD operations before and after writes to validate, transform, and log data.
Lifecycle hooks allow you to intercept CRUD operations before and after database mutations to normalize payloads, validate business logic, or trigger side effects.
Minimal Example
Configure hooks on a CRUD resource to normalize input before saving and log after saving. slug has no create permission, so clients can't send it; the hook always derives it:
import {
defineDatabase,
defineService,
sqliteTable,
text,
} from "@brickkit/core";
import { crud } from "@brickkit/crud";
export const articles = sqliteTable("articles", {
id: text("id")
.primaryKey()
.$defaultFn(() => crypto.randomUUID()),
title: text("title").notNull(),
slug: text("slug").notNull(),
});
const database = defineDatabase({ tables: { articles } });
export const articlesService = defineService("articles", { database });
export const article = articlesService
.resource({ name: "article", table: articles, id: articles.id })
.use(
crud({
access: "public",
fields: {
id: { read: true },
title: { read: true, create: true, update: true },
slug: { read: true },
},
hooks: {
beforeCreate: async ({ data, error }) => {
// Normalize input data in place
const title = String(data.title ?? "").trim();
if (!title) {
return error.BAD_REQUEST("Article title cannot be blank");
}
data.title = title;
// Hooks may set columns clients can't write
data.slug = title.toLowerCase().replace(/\s+/g, "-");
},
afterCreate: async ({ row, ctx }) => {
ctx.logger.info(`Article created: ${row.id} (${row.title})`);
},
},
}),
);Schema
These columns match the Drizzle tables in the example. Defaults marked as application defaults run in Drizzle, rather than in SQL.
Table Name: articles
| Field | Type | Description |
|---|---|---|
id | text | Row identifier. PK Default: crypto.randomUUID() (application) |
title | text | Display title. |
slug | text | URL slug. |
Available CRUD Hooks
All hooks are declared inside the hooks configuration of crud():
Hooks run after input validation, authorize, and scope. Every hook except afterCommit runs inside the write's transaction and receives it as tx.
| Hook | Arguments | Timing | Common Use Cases |
|---|---|---|---|
beforeCreate | { data, ctx, error, tx } | Before INSERT, in the transaction | Normalizing input, naming, permission validation |
afterCreate | { row, ctx, error, tx } | After INSERT, in the transaction | Child rows, audit rows, counters in other tables |
beforeUpdate | { id, data, ctx, error, tx } | Before UPDATE, in the transaction | Field mutation validation, updated timestamp stamping |
afterUpdate | { id, row, ctx, error, tx } | After UPDATE, in the transaction | Keeping related tables in step, audit rows |
beforeDelete | { id, ctx, error, tx } | Before DELETE, in the transaction | Cascade checks, deleting child rows |
afterDelete | { id, ctx, error, tx } | After DELETE, in the transaction | Cleaning up related rows |
afterCommit | { operation, id, row?, ctx } | After the transaction commits | Cache clears, realtime publishes, search index updates |
Bulk operations (bulkCreate, bulkUpdate, bulkDelete) fire the same hooks once per row, in item order, all inside the batch's one transaction. Each row's afterCommit runs after the whole batch commits.
row in afterCreate and afterUpdate is the full database row, including columns without read permission. The response is still limited to readable fields.
Mutating Input in before* Hooks
This is the supported place to adjust or normalize input before it is written. Before hooks receive data, a copy of the validated write payload (the create input, or update's data object). You can mutate fields or add values for columns clients can't write. Every key must be a column of the table, or the call fails with a 500. An update whose data is empty after beforeUpdate is rejected with BAD_REQUEST.
hooks: {
beforeCreate: async ({ data, ctx }) => {
// Inject tenant and author from authenticated context
data.tenantId = ctx.tenantId;
data.createdBy = ctx.user?.id;
},
beforeUpdate: async ({ data }) => {
if (typeof data.displayName === "string") {
data.displayName = data.displayName.trim();
}
},
}Aborting Writes with Error Helpers
Hooks receive the standard error builder (BAD_REQUEST, UNAUTHORIZED, FORBIDDEN, NOT_FOUND, CONFLICT, INTERNAL_SERVER_ERROR). Calling a helper throws an ActionExecutionError with that code and status.
A hook runs inside the write's transaction, so throwing in any before* or after* hook rolls back the whole operation: the row, anything the hook wrote through tx, and, for a bulk operation, every other item in the batch. Error helpers return their code and status to the client. Any other error is a 500.
hooks: {
beforeCreate: async ({ data, ctx, error }) => {
if (!ctx.user) {
return error.UNAUTHORIZED("Sign in to comment");
}
const trimmed = String(data.body ?? "").trim();
if (trimmed.length < 3) {
error.BAD_REQUEST("Comment must be at least 3 characters long");
}
},
}Writing Other Tables in the Same Transaction
Write through tx to make changes that commit or roll back with the row. To call another CRUD resource, pass tx as its db so the call joins the transaction:
hooks: {
afterCreate: async ({ row, tx, ctx }) => {
await tx.insert(ledger).values({ invoiceId: row.id, amount: row.total });
await auditLog.create.run({ note: `invoice ${row.id}` }, { ...ctx, db: tx });
},
}A write made through ctx.db instead of tx is not part of the transaction on Postgres. On SQLite it joins anyway, because the database has one connection.
Naming and Generated IDs
Set the ID or name in beforeCreate. Because the hook runs in the transaction, it can take the next number from a counter table without racing another insert:
hooks: {
beforeCreate: async ({ data, tx }) => {
const [series] = await tx
.update(namingSeries)
.set({ current: sql`${namingSeries.current} + 1` })
.where(eq(namingSeries.prefix, "LEAD"))
.returning();
data.name = `LEAD-${String(series.current).padStart(5, "0")}`;
},
}For other strategies you don't need a hook. Leave an autoincrement or $defaultFn() key to the database or Drizzle. For a hash, set data.id in beforeCreate. To let callers choose the ID, give the key create: true (see Primary Keys).
Child Rows
CRUD has no input field for child rows yet. To write a parent and its child rows in one transaction, use an action that runs both resources' operations on the same tx:
import { runInTransaction, t } from "@brickkit/core";
export const createQuote = quotesService.action({
name: "createQuote",
input: t.Object({
title: t.String(),
items: t.Array(t.Object({ sku: t.String(), qty: t.Integer() })),
}),
execute: ({ input, ctx }) =>
runInTransaction(ctx.db, async (tx) => {
const joined = { ...ctx, db: tx };
const parent = await quote.create.run({ title: input.title }, joined);
await quoteItem.bulkCreate.run(
{
items: input.items.map((item, idx) => ({
...item,
parent: parent.id,
idx,
})),
},
joined,
);
return parent;
}),
});Both resources' hooks run in that transaction, and each afterCommit waits for it to commit. To delete child rows with their parent, delete them through tx in beforeDelete.
Reacting After the Commit
afterCommit runs once the transaction has committed, and never for a write that rolled back. Use it for side effects outside the database, such as clearing a cache or publishing a realtime update:
hooks: {
afterCommit: async ({ operation, id, row }) => {
cache.delete(`lead:${id}`);
realtime.publish("lead", { operation, id, row });
},
}row is the full written row for create and update, and absent for delete. The write is already committed, so an error thrown in afterCommit is logged with ctx.logger and the client still gets its result. When the write runs inside an outer transaction, such as a hook of another resource or a bulk operation, afterCommit waits for that outer transaction to commit.
afterCommit runs in the request, so a slow hook slows the response. For work that must not be lost, such as sending an email, listen for the events that generated writes emit: they are recorded in the same transaction as the row and delivered with retries.