Hooks are functions that Prorm runs automatically at well-defined points in a
model's lifecycle — before and after validation, creation, updates, deletes,
and finds. They let you hash a password before it is written, stamp an audit
field, cascade side effects, or veto an operation by throwing — all without
scattering that logic across every call site.Every hook is dispatched through the model's HooksManager, which stores the
handlers you register and invokes them in registration order. This guide covers
the complete set of lifecycle events, how to attach handlers, what arguments
they receive, the order in which they fire, and some practical patterns.[!NOTE]
Every order and argument on this page was recorded by registering all the
hooks on a prorm.define() model (SQLite) and logging each call alongside the
SQL it produced. The scripts are ordinary Prorm code; if you depend on an
order, a test that records it the same way is cheap insurance.
Firing order#
The full create path — Model.create(), save() on a new instance, and each
row of bulkCreate(rows, { individualHooks: true }):beforeCreate runs before beforeSave, and afterCreate before
afterSave. If validation fails, the sequence stops after beforeValidate:
afterValidate and everything after it are skipped and a ValidationError is
thrown.The update path — instance.update(values) and save() on a loaded, changed
instance — runs the per-instance update hooks and the bulk pair, because the
single-row write goes through the same UPDATE machinery as Model.update():beforeSave and afterSave wrap both create and update, so logic that
applies to either belongs there rather than duplicated across the pair. Inside
a transaction the hooks receive the transaction in options.transaction, so a
throw rolls back the write along with anything the hook did on it.The lifecycle hooks that exist#
Prorm defines these hooks (the HookName union / ModelHooks interface). They
come in before* / after* pairs:| Hook | Fires around |
|---|
beforeValidate / afterValidate | instance validation on the create path |
beforeCreate / afterCreate | inserting a single record |
beforeUpdate / afterUpdate | updating — one instance, or once per Model.update() call |
beforeDestroy / afterDestroy | deleting — one instance, or once per Model.destroy() call |
beforeSave / afterSave | both insert and update of an instance |
beforeBulkCreate / afterBulkCreate | Model.bulkCreate() |
beforeBulkUpdate / afterBulkUpdate | every UPDATE, static or instance |
beforeBulkDestroy / afterBulkDestroy | every delete, static or instance |
beforeFind / afterFind | findAll / findOne / findByPk |
beforeCount | Model.count() |
beforeUpsert / afterUpsert | Model.upsert() |
beforeReload / afterReload are also valid names (they are ModelHook
members). A define() model's reload() fires no hook: it re-reads the row
with hooks: false, so a beforeFind that rewrites the where cannot make
it load a different row. Earlier releases fired beforeFind / afterFind
for it.Defining hooks in define()#
The most common way to attach hooks is the hooks object in the third argument
of define(). Each key is a hook name and each value is a handler.import { Prorm, DataTypes } from 'ts-prorm-orm';
const prorm = new Prorm({ dialect: 'sqlite', storage: ':memory:' });
await prorm.connect();
const User = prorm.define(
'User',
{
id: { type: DataTypes.INTEGER(), primaryKey: true, autoIncrement: true },
name: { type: DataTypes.STRING(100), allowNull: false },
email: { type: DataTypes.STRING(255), allowNull: false },
status: { type: DataTypes.STRING(20), defaultValue: 'pending' },
},
{
tableName: 'users',
timestamps: true,
hooks: {
beforeCreate: async (values: any) => {
// Normalise data before it is written. On the create path this is the
// plain values object: assign properties, there is no get()/set() yet.
values.status = 'active';
},
afterCreate: async (instance) => {
console.log(`Created user ${instance.get('id')}`);
},
},
},
);
Handlers may be synchronous or async; Prorm always awaits them, so returning
a promise is fully supported. A value a before* hook assigns is written:
the INSERT is built after beforeCreate / beforeSave have run.Attaching hooks after definition#
You can also register hooks on an already-defined model with hook(name, fn),
or with addHook(name, id, fn), which gives the handler an id you can remove it
by later (registering the same id again replaces the handler instead of
stacking a second copy). A common layout keeps each cross-cutting concern in its own
module that registers against the model at startup:src/
db/
index.ts # defines the models, then imports ./hooks
hooks/
normalise-user.ts # beforeCreate: trim and lower-case the email
audit.ts # afterSave / afterDestroy: write audit rows
cache.ts # afterSave / afterDestroy: evict cache keys
import type { ModelStatic } from 'ts-prorm-orm';
export function registerNormaliseUser(User: ModelStatic) {
User.addHook('beforeCreate', 'normalise-user', (user: any) => {
user.email = String(user.email).trim().toLowerCase();
user.slug = String(user.name).toLowerCase().replace(/\s+/g, '-');
});
}
await User.create({ email: ' Ada@Example.COM ', name: 'Ada Lovelace' });
Registration is additive — calling hook() twice for the same event registers
two handlers, and both run in the order they were added. To inspect or remove
handlers:User.hasHook('beforeCreate'); // => true
// Remove one handler by the id it was registered with…
User.removeHook('beforeCreate', 'normalise-user');
// …or by the handler function itself…
const stamp = (user: any) => { user.importedAt = new Date(); };
User.addHook('beforeCreate', stamp);
User.removeHook('beforeCreate', stamp);
// …or every handler for an event.
User.removeHook('beforeCreate');
User.hasHook('beforeCreate'); // => false
[!NOTE]
Before 4.9.2, removeHook removed by id only: passing the handler
function left it registered and running. It now matches either.The named shortcuts (User.beforeUpdate(fn), User.afterDestroy(fn), …)
exist on decorator (Model class) models only; on a define() model they
are undefined, so use hook('beforeUpdate', fn).
Hook arguments#
What each hook receives depends on the call that fired it — an instance for
instance operations, the options object for static ones:| Hook, fired by | Arguments |
|---|
beforeValidate, afterValidate, beforeCreate, beforeSave on the create path | (record, options) — the values about to be inserted, with the instance API (get, set, changed(), dataValues, isNewRecord: true) |
afterCreate, afterSave on the create path | (instance, options) |
update and destroy hooks from save / instance.update / instance.destroy | (instance, options) |
beforeUpdate / afterUpdate, from static Model.update(values, opts) | (values, options) — a plain object, not an instance |
beforeDestroy / afterDestroy, from static Model.destroy(opts) | (options) — with where |
beforeBulkUpdate / beforeBulkDestroy | (options) — with where (and attributes for updates) |
beforeBulkCreate / afterBulkCreate | (instances, options) |
beforeFind | (findOptions) — mutable |
afterFind | (instances, findOptions) |
beforeCount | (countOptions) |
beforeUpsert | (values) |
[!IMPORTANT]
Before the INSERT there is no stored row yet: on the create path
beforeValidate, afterValidate, beforeCreate and beforeSave get the
values about to be inserted with the instance API over them —
record.get('email'), record.set({ slug }), record.setDataValue(…),
record.changed('email') (every attribute given is a change) and
record.dataValues. Plain assignment (record.email = …) works too, and
whatever a hook writes goes into the INSERT. It has no save(),
reload() or destroy(); from afterCreate on the argument is a real
instance. (Before the next release after 4.9.4, a define() model handed
these hooks the plain values object, with no get or set.)
[!CAUTION]
The same beforeUpdate handler is called with an instance from
user.update() and with a plain values object from User.update(). A
handler that calls instance.get() or instance.changed() throws on the
static path. Check before you use it:User.addHook('beforeUpdate', 'lowercase-email', (target) => {
const isInstance = typeof (target as any).get === 'function';
const email = isInstance ? target.get('email') : (target as any).email;
if (typeof email === 'string') {
isInstance ? target.set('email', email.toLowerCase()) : ((target as any).email = email.toLowerCase());
}
});
options carries the triggering call's options (a HookOptions), including
transaction. Use options.transaction to keep any additional queries you run
inside the same transaction:User.hook('beforeCreate', async (instance, options) => {
instance.slug = slugify(instance.name);
await AuditEntry.create(
{ action: 'user.create', name: instance.name },
{ transaction: options?.transaction },
);
});
Bulk hooks receive the array of records for creates:User.hook('beforeBulkCreate', (instances, options) => {
for (const instance of instances ?? []) {
instance.status = 'imported';
}
});
Find hooks can rewrite the query before it runs. A beforeFind that adds a
condition — a tenant filter, say — changes the SQL for every finder:User.hook('beforeFind', (findOptions) => {
findOptions.where = { ...(findOptions.where ?? {}), status: 'active' };
});
User.hook('afterFind', (instances) => {
console.log(`Loaded ${instances.length} user(s)`);
});
await User.findAll({ where: { email: 'ada@example.com' } });
A beforeFind handler may also return a new options object instead of
mutating the one it was given; with several handlers, each one receives what
the previous returned.Ordering#
Hooks fire in a fixed sequence per operation. Within a single event, multiple
registered handlers run in the order they were added. The sequences below are
exactly what was recorded, statement included:Model.create(values) · build(values).save() · bulkCreate(rows, { individualHooks: true }), per row
beforeValidate → afterValidate → beforeCreate → beforeSave
→ INSERT
→ afterCreate → afterSave
Validation failure:
beforeValidate → ValidationError thrown (nothing else runs, nothing is sent)
instance.update(values) · instance.save() on a loaded row
beforeUpdate → beforeSave → beforeBulkUpdate
→ UPDATE
→ afterBulkUpdate → afterUpdate → afterSave
Model.update(values, { where }) — with or without individualHooks
beforeUpdate(values) → beforeBulkUpdate(options)
→ UPDATE
→ afterUpdate → afterBulkUpdate
instance.destroy()
beforeDestroy → beforeBulkDestroy
→ DELETE (or UPDATE … SET "deletedAt" on a paranoid model)
→ afterBulkDestroy → afterDestroy
Model.destroy({ where }) — with or without individualHooks
beforeDestroy(options) → beforeBulkDestroy(options)
→ DELETE / UPDATE
→ afterDestroy → afterBulkDestroy
findAll · findOne · findByPk
beforeFind → SELECT → afterFind
instance.reload()
SELECT (no hooks)
count
beforeCount → SELECT COUNT(*)
upsert
beforeUpsert
→ beforeFind → SELECT → afterFind
→ INSERT … ON CONFLICT DO UPDATE
→ beforeFind → SELECT → afterFind
→ afterUpsert
Model.bulkCreate(rows)
beforeBulkCreate
→ INSERT (one per row)
→ afterBulkCreate
No validation and no per-row hooks.
Model.bulkCreate(rows, { individualHooks: true })
beforeBulkCreate
→ for each row: beforeValidate → afterValidate → beforeCreate → beforeSave → INSERT → afterCreate → afterSave
→ afterBulkCreate
Things this order implies:individualHooks only matters for bulkCreate. Model.update() and
Model.destroy() already call beforeUpdate / beforeDestroy once per
call, with the options, and passing individualHooks: true does not change
that — it does not load and visit each row.
Updates skip the validate hooks. instance.update() still validates
(see Validation), but
beforeValidate / afterValidate do not fire for it; put update-time
normalisation in beforeUpdate or beforeSave. A handler on beforeBulkUpdate sees instance updates too, so do not
treat it as "someone ran a mass update".
// Bulk import that should go through the same normalisation as a signup.
await User.bulkCreate(rows, { individualHooks: true });
Skipping hooks#
Every write accepts hooks: false to bypass hook execution — useful for seeds,
migrations, or internal maintenance where you do not want side effects to fire.await User.create({ name: 'System', email: 'system@example.com' }, {
hooks: false,
});
By default hooks are on (hooks defaults to true); passing hooks: false is
the only value that disables them.hooks: false is honoured by create(), bulkCreate(), instance.save()
(new or already saved), instance.update(), the static Model.update() and
Model.destroy(), and findAll(): no model hook fires, including the bulk
pair around the INSERT, UPDATE or DELETE.[!NOTE]
Before 4.9.2, instance.save({ hooks: false }) on an already-saved row
still fired beforeUpdate and beforeBulkUpdate, and the static
Model.update() and findAll() ignored hooks: false. Until the next
release after 4.9.4, the static Model.destroy({ where, hooks: false })
still fired beforeBulkDestroy / afterBulkDestroy, and a define()
model's bulkCreate(rows, { hooks: false }) still fired
beforeBulkCreate / afterBulkCreate.
Validation hooks#
beforeValidate / afterValidate fire around validation on the create path,
and around instance.validateRules() when you opt in:const result = await user.validateRules({ hooks: true });
beforeValidate is the right place to coerce or normalise input so that the
values that reach the validators are already clean:User.hook('beforeValidate', (instance) => {
if (typeof instance.email === 'string') {
instance.email = instance.email.trim().toLowerCase();
}
});
Before and after, with an isEmail rule on email:Practical patterns#
Hashing a password before write. A beforeCreate hook keeps hashing logic in
one place (for new code, the secure attribute option does
this for you):declare function hashPassword(plain: string): Promise<string>; // your own, e.g. argon2
User.hook('beforeCreate', async (instance) => {
instance.password = await hashPassword(instance.password);
});
Generating a value the database cannot. A beforeCreate hook is also the
reliable way to fill a UUID or slug column, because what it assigns is part of
the INSERT (see the warning in Data types):import { randomUUID } from 'node:crypto';
User.hook('beforeCreate', (instance) => {
if (!instance.publicId) instance.publicId = randomUUID();
});
Vetoing an operation. Throwing from any before* hook aborts the operation —
the error propagates to the caller unchanged and the write never happens.User.hook('beforeDestroy', (instance) => {
if (instance.role === 'owner') {
throw new Error('Cannot delete the workspace owner');
}
});
Error: Cannot delete the workspace owner
Cascading side effects transactionally. Use options.transaction so the side
effect commits or rolls back with the triggering write:User.hook('afterCreate', async (instance, options) => {
await Profile.create(
{ userId: instance.id },
{ transaction: options?.transaction },
);
});
await prorm.transaction(async (t) => {
await User.create({ name: 'Ada', email: 'ada@example.com' }, { transaction: t });
// the Profile insert above ran on `t`; a throw here rolls back both rows
});
Cache invalidation on delete. afterDestroy runs once the row is gone:User.hook('afterDestroy', (instance) => {
cache.evict(`user:${instance.id}`);
});
Because hooks are just functions registered on the model, you can compose them
freely — layer several handlers on one event, register cross-cutting concerns
(audit, cache, search indexing) from separate modules, and disable them per-call
with hooks: false whenever you need the raw operation.
Next: Transactions — making several writes succeed or fail together.Validation — what runs between beforeValidate and afterValidate Enums — ModelHook / PrormHook instead of strings Modified at 2026-10-04 00:40:16