Record hooks — beforeInsert to afterDelete
Run custom code at interception points in the ObjectQL execution pipeline — before/after insert, update, delete, and find
Hooks are the data-layer "logic layer": they run custom code at interception
points in the ObjectQL execution pipeline (before/after insert, update, delete,
find, etc.). The construct is Hook, imported from @objectstack/spec/data.
A hook targets one or more objects and subscribes to one or more lifecycle
events. Each event is a combined timing+action enum value, e.g.
beforeInsert, beforeUpdate, afterUpdate, afterDelete (read-side events
such as beforeFind/afterFind are also available).
Hooks vs flows
Hooks and flows overlap on record-triggered logic —
a flow's record_change trigger fires on the same lifecycle events — so pick
the layer before writing either. The working rule: a flow is the default
surface for application logic; a hook is the backstop for what a node graph
cannot express.
| You need… | Reach for |
|---|---|
| Side effects after a save — create records, notify, call HTTP, request approval | Flow (record_change) |
| Anything that pauses: approvals, screens, timers, signals | Flow — a hook runs inline and cannot pause |
Scheduled or date-relative sweeps ("30 days before end_date") | Flow (schedule / timeRelative) — which declares the organization it runs as |
| Mutating the pending record in the same write, before it is saved | Before hook |
| An invariant enforced on every write path, across objects, no matter who writes | Hook — the backstop duty itself |
Read-side interception (beforeFind / afterFind) | Hook — flows have no read events |
Two structural reasons to prefer the flow when either could work:
- A flow's writes are structured metadata; a hook body is code. An
update_recordnode'sfieldsis structural config thatos validatechecks — readonly targets, template dialects, declared expression slots. A hook body's write set is checked too, but only for the literal patterns a parser can recognise (see Hook & Action Bodies). Field existence is checked on both surfaces, at different strengths: a hook body gets a warning, anupdate_recordnode a gating error (flow-node-write-unknown-field) — itsfieldsis a literal map next to a literalobjectName, so nothing could have mis-read it. Writability is now gated on both: writing areadonlyfield throughctx.apiishook-api-update-readonly-field, the hook-side sibling of the flow node'sflow-update-readonly-field(see Writing areadonlyfield) — the two questions differ because areadonlydeclaration and a literalctx.apiupdate are both visible in the stack, while a field's existence may depend on a package the build cannot see. - A flow reviews as data. The node graph diffs field-by-field and renders in the Console designer with per-node run history; a hook body reviews as code only.
Logic that genuinely needs code still doesn't have to be a hook: a flow
script node calling a function registered via defineStack({ functions })
keeps the orchestration in checked metadata and the code in one named,
testable unit.
Targeting objects
object takes three forms, and the third one carries a review cost the other
two do not:
object: 'account' // one object
object: ['account', 'contact'] // a named set
object: '*' // every object in the tenantAn empty target is refused, not treated as "no target". '', [] and
[''] used to parse; the binder then widened '' and [] to the wildcard, so
a blank target registered the hook on every object, on every event it
listed, with no diagnostic. ([''] failed the other way — an object name
nothing matches, a hook that could never fire.) All three are now a parse
error naming the two spellings that work. A wildcard hook stays entirely
legitimate; it just has to be spelled '*', so it is a choice a reviewer
sees in the diff rather than a default someone fell into (#4001).
Wildcard hooks earn a higher review bar
object: '*' is the right tool for genuinely cross-cutting concerns — audit
trails, provenance stamping, tenant-wide guards. It is also the broadest thing
a hook can be, so review it as such:
- Blast radius is every object, including ones added later. A wildcard hook written today runs against objects that do not exist yet, whose fields it was never checked against. Prefer a named set when the list is actually known.
- Cost multiplies by object count and write volume. A
beforeUpdatewildcard hook runs on every write in the tenant; anything non-trivial in it belongs behind acondition(evaluated before the handler) rather than an earlyreturninside the body. - Reads and writes both widen. A wildcard hook holding an L2 body with
api.writecan write anywhere. Itsctx.inputwrites are also the one shape the write-set lint has to skip — with no single target object there is nothing to resolve field names against — so a wildcard write set is the least verifiable shape in the system.
Where a wildcard is the honest answer, say so in description — it is the one
place a reviewer can find out why the broad target was chosen.
The condition gate
A declarative hook can carry a CEL condition, evaluated before the handler:
the hook fires only when it is true. Three things about it changed in protocol 17,
and the first is breaking.
An unevaluable condition aborts the operation (#4775). A condition the platform
could not work out used to emit a logger.warn and return false — the hook simply
did not fire. "The condition said no" and "the platform could not evaluate the
condition" carry opposite risks depending on the hook: swallowed into a before*
guard it silently lets the write through; swallowed into an audit hook it silently
drops the record. They are now distinct outcomes, and the second fails the write.
Hooks that have been getting by on that skip will start failing — that is how you
find out they were never enforcing anything. Over the API the refused write answers
400 with the code VALIDATION_ERROR, and its message names the hook and the fault,
never the condition's source — the same status a validation rule that cannot be
evaluated answers.
The condition reads the record, not the payload (#4770). It used to evaluate
against ctx.input.data — only the fields the current write happened to carry — so
condition: "record.done == true" did not run on the most ordinary updates there
are (change the status, change the assignee), because done was not in the payload.
It now evaluates against stored ⊕ payload: the prior record overlaid with this
write's data, total over the object's declared fields (null for a declared field in
neither), with the payload winning for the fields it carries. Undeclared or typo'd
keys stay unresolvable — record.stauts is an error, not a silent false.
previous is bound, so a condition can express a transition (#4784). The scope
was a single { record } root, which made the published previous form
(previous.status != 'escalated' && record.status == 'escalated', and the legacy
OLD.x / ISCHANGED(x) mappings) abort with No such key: previous. It is now
bound alongside record, built by the same helper the validation side uses, so one
CEL expression means one thing on both surfaces.
// "after a task transitions to done" — not "whenever a done task is written"
condition: P`previous.done != true && record.done == true`Because record now means the record's state, record.done == true alone is true
on every update of an already-done row. If you wrote a condition under the old
payload semantics expecting "the write that changed it", add the previous half.
A field that can be null needs a != null guard before <, >, + and the
rest — CEL has no ordering or arithmetic over null, so the condition faults and
the write fails. os build and the publish gate refuse the unguarded form. That
holds for the columns the platform adds as well: owner_id, created_by,
updated_by, owning_business_unit_id, queue and organization_id are null on
a row a system write, a seed or a guest left them empty in, so write
record.owner_id != null && record.owner_id > 'a'. created_at and updated_at
are stamped on every stored row and need no guard, except in a beforeInsert hook:
one with a priority below 10 runs before the stamp and reads them as null, so
os build and the publish gate ask for the guard at every beforeInsert hook.
Elevation — runAs
A hook's ctx.api runs with the context of the write that fired it. That is usually what you want, and it is the one thing that makes a column both guarded and maintained impossible to express: author editable: false (or readonly: true) so nobody hand-writes the column, and the hook that computes it is refused by the very same check. The guard and the legitimate writer are the same door.
runAs is the declaration that separates them. It is the same key a flow declares, and 'system' and 'user' mean there exactly what they mean here, plus one value only a hook can have — a flow establishes its identity from nothing, so it has no context to inherit:
runAs | The hook's ctx.api runs as |
|---|---|
'inherit' (default) | the context of the triggering write — the behaviour every hook had before this key existed. |
'system' | elevated: an RLS-bypassing system principal. Row and field permissions do not apply, and the static readonly strip is skipped. Elevation stops at identity assignment: an insert, update, delete, transfer, restore or purge of sys_user_position, sys_user_permission_set, sys_invitation or sys_member from an app-authored hook's system context (runAs: 'system', a system context it inherits, or ctx.api.sudo()) is refused with PERMISSION_DENIED, and a runAs: 'system' hook whose language: 'js' body writes one of them by name through ctx.api.object('…') is refused when it is saved — grant positions and permission sets from a hook with runAs: 'user', so the delegated-administration gate judges the user it acts for, and change invitations and memberships through the organization endpoints the refusal names (row 1b). |
'user' | the triggering user, so the hook can never exceed that user's grants. A hook fired by a write that carried no user has no identity to scope to, so its ctx.api data operations are refused (HOOK_UNSCOPED_DATA_ACCESS) rather than run unscoped. |
{
name: 'stamp_account_grade',
object: 'rating',
events: ['afterInsert'],
runAs: 'system', // this hook maintains a column nobody may hand-write
body: {
language: 'js',
source: `await ctx.api.object('account').update({ id: ctx.input.account_id, current_grade: ctx.input.grade });`,
capabilities: ['api.read', 'api.write'],
},
}Four things worth knowing before you reach for it:
- It scopes
ctx.api, and nothing else. Theconditiongate,ctx.session, thereadonlystrip applied to the hook's ownctx.inputpayload, andasyncbehaviour all still read the triggering operation's context. DeclaringrunAs: 'system'does not elevate the write that fired the hook. - Elevation is authorization, not anonymity. The triggering user rides along, so an elevated write still stamps
created_by/updated_bywith the operator and still appears under their name in the audit log. You do not trade the audit trail for the write. - Both surfaces honour it — an in-process
handlerand a sandboxedbodyalike. This is the reasonrunAsexists rather thanctx.api.sudo():sudo()is real only in-process, so the same source passed a unit test and threw in production. 'user'is a narrowing, and it fails closed. It cannot resolve to a grant: a hook that declares it and finds no trigger user refuses its data operations instead of running them with no principal at all.
Before Hook
Mutate the incoming record before it is saved. The engine exposes the pending
record's fields directly on ctx.input (a flat view over the internal
{ data, options } wrapper — reads and writes of record fields route through
ctx.input.data):
On update, "the incoming record" means the record the engine intends to
persist — a caller-supplied value for a readonly field is not on it, and the
caller's submission is on ctx.submitted instead (diagnostics only). On a
create the same value is withheld from beforeInsert too: the field holds
its defaultValue or no key, and a create has no ctx.submitted. See
Static readonly fields on the write path
for the five rules and the migration.
`id` / `options` / `ast` / `data` are RESERVED on the flat `ctx.input` face
These four names always resolve to the envelope, never to a record field —
even if your object declares a field with one of those names. A field named
id (or options / ast / data) still round-trips through storage
exactly as declared; it is simply unreachable as ctx.input.<name>. Read it
at ctx.input.data.<name> instead:
handler: async (ctx) => {
ctx.input.id; // the row this write targets (or undefined on insert) — NEVER the payload's own `id` field
ctx.input.data.id; // the payload's own `id` field, if the object declares one
};This applies to every read of these names through ctx.input — direct
access, Object.keys/for-in, spread, and Object.entries all agree on the
envelope's value for a reserved name (packages/objectql/src/hook-wrappers.ts,
#12601).
A symbol key is refused, not stored
A record payload is a declarable, string-keyed field set — no metadata schema
can declare a symbol field. Writing one onto ctx.input, whether by
assignment or Object.defineProperty, throws a TypeError naming the key and
the surface instead of silently accepting it:
const cacheKey = Symbol('cache-entry');
handler: async (ctx) => {
ctx.input[cacheKey] = value; // throws: symbol keys are not a valid record-payload field
};This most often happens by accident — spreading an object that carries a
symbol-keyed cache entry onto the payload. Use a string key, or keep the value
off the payload entirely if it is not meant to be stored (packages/objectql/src/hook-wrappers.ts,
#12603).
import { Hook } from '@objectstack/spec/data';
export const AccountBeforeWrite: Hook = {
name: 'account_before_write',
object: 'account',
events: ['beforeInsert', 'beforeUpdate'],
handler: async (ctx) => {
const record = ctx.input as Record<string, any>;
// Normalize phone numbers
if (record.phone) {
record.phone = normalizePhone(record.phone);
}
// Auto-populate from website
if (!record.industry && record.website) {
record.industry = await lookupIndustry(record.website);
}
},
};After Hook
React after a record is written — but before the enclosing unit of work
commits, so read After hooks run inside the unit of
work before giving one a side effect
outside the engine. Use ctx.previous for the pre-change snapshot and
ctx.api.object('x') for cross-object writes:
export const OpportunityAfterUpdate: Hook = {
name: 'opportunity_after_update',
object: 'opportunity',
events: ['afterUpdate'],
handler: async (ctx) => {
const opp = ctx.result as Record<string, any>;
const wasWon = ctx.previous?.stage === 'closed_won';
if (opp.stage === 'closed_won' && !wasWon) {
// Create a contract via the scoped cross-object API
await ctx.api.object('contract').insert({
account: opp.account,
opportunity: opp.id,
contract_value: opp.amount,
start_date: new Date(),
});
}
},
};After hooks run inside the unit of work
An after* hook does not mean "the write happened". It means the write
has been requested and will happen unless this unit of work is undone.
afterInsert, afterUpdate and afterDelete are dispatched before the
enclosing transaction commits, so a later refusal in the same unit can roll the
row back after your handler has already run. That is true of a blocking
hook, the default. An async: true hook is dispatched there too, but does not
run there: see async: true after hooks run after the
commit.
Five ordinary operations put a write inside such a unit:
| Operation | What is inside the transaction |
|---|---|
Any write to an object with an after* hook that can abort it: a blocking one whose onError is abort (the default), or one carrying a condition, whatever its onError and async (a condition that cannot be evaluated aborts the write) | The write and every after* hook it dispatches, so that hook's abort rolls the row back. Not opened on an object outside the default datasource, or on a driver with no transactions: there the row stays stored after an abort |
Any write to an object with a before* hook on the same verb (beforeInsert for an insert, beforeUpdate for an update, beforeDelete for a delete), declared in metadata, whatever its onError | The write, its before* hooks and every ctx.api write they make, so a refusal later in the same write (a declared validation, a later before* hook, a driver constraint) rolls those writes back with it. Not opened on an object outside the default datasource, or on a driver with no transactions: there a before* hook's writes stay stored after a refusal. A hook registered in code with registerHook opens no unit |
A by-id delete() that cascades to dependent records | Each cascaded child's afterDelete. The parent's own afterDelete runs after that unit closes, unless the row above opened one around the whole delete |
batchData / deleteManyData with atomic: true | Every member's after* — the batch aborts and rolls back on the first failure |
Any write you wrapped yourself in ctx.api.transaction(...) or engine.transaction(...) | Everything in the callback |
What this means when you write a blocking handler:
- Effects that go back through the engine are safe. Writes made with
ctx.api.object('x')join the same transaction and roll back with everything else — that is what makes an in-engine audit or projection hook correct in the first place. - Effects that leave the engine are yours to make rollback-tolerant. A webhook, a notification, an email, an external search-index update or a file deletion has already gone out when the rollback happens, announcing a change that did not survive. Make the effect idempotent and reconcilable, or hand it to a worker that re-reads the record before acting rather than trusting the event on its own.
Before hooks carry no such caveat: they run before the write is issued, and
throwing from one refuses the operation outright. A before* hook's own
ctx.api writes are inside the unit its row of the table above opens, so they
follow the same rules: a refusal anywhere in the write rolls them back, with no
per-hook opt-out, and a write to an object on another datasource is refused
with CrossDatasourceTransactionWriteError. The one exception is an
append-only ledger on another datasource (an object whose lifecycle.class is
audit, telemetry or event): it is written outside the unit and survives
the rollback. Keep the objects a before* hook
writes on the default datasource; on MongoDB, run it as a replica set, which
any unit needs.
On PostgreSQL a statement that fails at the database aborts the whole unit
(25P02, "current transaction is aborted"), and the unit takes no savepoint
around a hook's ctx.api write. A before* hook whose ctx.api statement
fails there therefore refuses the write it belongs to, even when the hook body
catches the error, onError: 'log' swallows it, or its retryPolicy re-runs
it. Check the condition before writing, or make that write from an after*
hook with async: true (not yet measured on PostgreSQL; tracked in
#34563).
For a blocking hook this is a deliberate, ruled semantics (#7477),
not an implementation detail awaiting a fix. Deferring a blocking after* to
commit time would move its own ctx.api writes outside the transaction the
write ran in, which is a worse guarantee than the one documented here. An
async: true hook has no such writes to keep: nothing awaits it, so its writes
never joined the unit, and it is the one that waits for the commit (below).
async: true after hooks run after the commit
An async: true hook on afterInsert, afterUpdate or afterDelete is not
awaited: the write returns without waiting for it, and the hook can neither
abort the write nor have its writes rolled back with it. Inside a unit of work
(any row of the table above) it therefore waits for that unit's outcome:
- The unit commits: the hook starts once the outermost unit has
committed, so its
ctx.apireads see the triggering write. A nestedtransaction()joins the outer unit, so its return is no commit. - The unit rolls back: the hook never runs. It does not announce a
write that did not survive, so an
asynchook is the one to give an effect outside the engine. To react to a write that was refused, use a blocking hook, or record the refusal where the write is made. - Outside any unit, or on a driver with no transactions: the hook starts at once, as the write is dispatched.
Either way its own ctx.api writes run outside the triggering unit, on their
own; a ctx.api.transaction(...) it opens is its own unit. An async
afterFind hook does not wait: a rollback does not undo a read, so it starts
when the read is dispatched, outside any unit, whatever the unit does next.
Refusing in the user's language — refusals
A hook that says "no" to a write throws. A sentence written into the throw reaches every caller in the language you wrote it in. To refuse in the caller's language, declare the refusals on the hook and throw a declared code. The runtime answers with the declared sentence, translated in the caller's locale, and with the declared status:
export const planGate = {
name: 'plan_gate',
object: 'production_plan',
events: ['beforeUpdate'],
refusals: {
CREDIT_LIMIT: { message: 'This plan exceeds the credit limit.', status: 409 },
VALIDATION_FAILED: {
message: 'This plan cannot be submitted.',
params: ['state'],
reasons: {
plan_locked: { message: 'The plan is {{ state }} and can no longer change.' },
second_primary: { message: 'This plant already has a primary plan.' },
},
},
},
handler: async (ctx) => {
if (ctx.previous?.locked) {
throw Object.assign(new Error('locked'), {
code: 'VALIDATION_FAILED',
reason: 'plan_locked',
params: { state: ctx.previous.state },
});
}
},
};- The code is the key. Each entry of
refusalsis keyed by the SCREAMING_SNAKE code the hook throws, and the caller's envelope carries that code. An entry has amessageand, optionally, a 4xxstatus(400 when absent). reasons— several sentences under one code. A gate with several refusals of the same class keeps one wire code and declares one snake_case reason per sentence. Throw{ code, reason }. The caller reads the reason's sentence, with the code and the status of the entry it sits under.params— names a sentence may fill. An entry that declaresparamsmay write{{ name }}holes over those names, in its ownmessageand in each reason. Throw the values asparams: { name: value }. A hole over any other name is refused when the hook is saved. An entry that declares noparamsis plain text, and every{{ }}hole in it is refused.- It works whichever way the hook is written. A TypeScript
handler(run in-process on a source boot such asbootStack(config), and lowered to ajsbody byos build) and a sandboxedjsbody answer the same envelope. - Loud on a mistake. A code the catalogue does not declare, or a reason a
code with
reasonsdoes not declare, is refused when the hook is saved if the hook names it literally in athrow. Otherwise it is refused when the hook runs, as a500that names the hook and the code. A throw with no code is refused the same way. An error actx.apicall raised and the hook let through unchanged, and a crash, pass through as they always did. Under a code that declares noreasons, areasonon the throw is not read: the entry's own sentence answers. - Translated by key. Each sentence has a key the translation bundle
writes,
hooks.<hook>.refusals.<CODE>.messageandhooks.<hook>.refusals.<CODE>.reasons.<REASON>.message;os i18n extractscaffolds them andos i18n checkcounts them. A translation keeps the entry's{{ }}holes. See Translations.
A hook that declares no refusals refuses exactly as before: the thrown
error's own code, status and message reach the caller.
Writing a sentence people read — texts
A sentence a hook writes into a record — the subject of the follow-up task it opens, the summary it logs — is read by the whole organization. Declare it on the hook and ask for it by key: the runtime answers it in the organization's language, never the language of the person whose save fired the hook.
export const leadFollowUp = {
name: 'lead_follow_up',
object: 'crm_lead',
events: ['afterUpdate'],
texts: {
follow_up_subject: { message: 'Follow up with qualified lead: {{ lead }}', params: ['lead'] },
},
handler: async (ctx) => {
if (ctx.input.status !== 'qualified' || ctx.previous?.status === 'qualified') return;
const subject = await ctx.text('follow_up_subject', { lead: ctx.input.name });
await ctx.api.object('crm_task').insert({ subject, related_to_lead: ctx.input.id });
},
};- The organization's language. The Localization setting when somebody set
it (Setup → Localization), else the app's
i18n.defaultLocale. A hook a person's save fires still writes in the organization's language — the record is data everyone reads, not a message to that person. - Translated first, filled after.
ctx.textpickshooks.<hook>.texts.<key>.messagein that language, then fills the{{ }}holes from theparamsyou pass. A text that declaresparamsmay write{{ name }}holes over those names, with an optional known formatter; one that declares none is plain text, and a hole in it is refused when the hook is saved. A hole over another name is refused at save; logic, an unknown formatter, an empty hole and{{ amount | currency }}with no code are refused byos validate,compileand the publish gate. - A missing translation never fails the hook. With no translation, or no
language to pick, the declared
messageis written. A translation whose holes do not render is dropped for the declaredmessage, filled. - An unreadable Localization setting rejects. When the settings service
cannot be read,
ctx.textrejects rather than write another language over the organization's choice. Catch it if the hook should write anyway. - Only declared text is translated. A string the hook builds itself is
written as it is. A key
textsdoes not declare is refused when the hook is saved if the hook names it literally inctx.text('key'), otherwise when the hook runs, as a500that names the hook and the key. - It works whichever way the hook is written — a TypeScript
handlerand a sandboxedjsbody get the samectx.text. Anexpressionbody cannot ask for one, sotextsis refused there. - Translated by key.
os i18n extractscaffoldshooks.<hook>.texts.<key>.messageandos i18n checkcounts it. See Translations.
Rows a hook wrote before it declared the text keep their text: nothing is rewritten.
Recipe — refuse overlapping time ranges
Leave and overtime requests share one rule: two live records of the same owner
may not cover the same time (a room or shift booking is the same rule grouped by
the room or the shift). There is no declarative key for it, and a validation
rule cannot see the other records, so write it as a before* hook on both
insert and update. This is the vetted form; rename its name (the refusal's
translation key follows it), its object and its fields:
import { defineHook } from '@objectstack/spec/data';
export default defineHook({
name: 'leave_request_no_overlap',
object: 'leave_request',
events: ['beforeInsert', 'beforeUpdate'],
runAs: 'system', // count the rows the saver cannot read too
refusals: { OVERLAP: { message: 'This overlaps another request of yours.', status: 409 } },
body: {
language: 'js',
capabilities: ['api.read'],
source: `
const DATE_ONLY = false; // true when start_at / end_at are date fields: the end day is booked too
const r = Object.assign({}, ctx.previous, ctx.input); // update: stored row under the patch
const off = ['rejected', 'cancelled'];
if (!r.owner_id || !r.start_at || !r.end_at || off.includes(r.status)) return;
const where = {
owner_id: r.owner_id,
status: { $nin: off }, // fail closed: a new status counts until listed here
start_at: DATE_ONLY ? { $lte: r.end_at } : { $lt: r.end_at }, // datetime is half-open:
end_at: DATE_ONLY ? { $gte: r.start_at } : { $gt: r.start_at }, // 18:00 end, 18:00 start is no overlap
};
if (ctx.previous) where.id = { $ne: ctx.previous.id }; // not the record itself
if (await ctx.api.object(ctx.object).count({ where }) > 0)
throw Object.assign(new Error(), { code: 'OVERLAP' });
`,
},
});Each line is there for a reason:
- Merge the stored row under the patch. On update
ctx.inputcarries only the fields this write changes, so a patch that movesstart_atalone must be judged with the storedend_at,owner_idandstatus. - Exclude the record itself with
id: { $ne: … }, or every update of a booking collides with its own stored row. - Name the ignored statuses with
$nin(or$ne), never the live ones with$in. A status added later then counts as live until someone decides otherwise, and a row with no status counts too. A record saved in an ignored status is not checked; reviving it into an overlap is refused. - Half-open ranges for
datetime.start < other.end && end > other.start: a booking ending at 18:00 and one starting at 18:00 do not overlap. - Inclusive end days for
date— setDATE_ONLY. A one-day leave hasstart == end, so the half-open test would let the same day be booked twice. WithDATE_ONLY = truethe template compares with<=/>=. The flag is needed because abefore*hook sees the value as it was written: adatefield also takes a full ISO instant or aDate, so the spelling does not say which kind the field is. The query reads each value as the day it stores. runAs: 'system'. The count must see rows the saver cannot read: a delegate filing for someone under private sharing, or a room booked by others. Without it the hook'sctx.apireads as the saver (see Elevation) and misses them. The hook only counts; the write itself still runs as the saver.ctx.api.object(ctx.object)counts in the object the hook fired on, so the body names no object.- A declared refusal. The body throws the code alone; the saver gets the
catalogue's fixed sentence (translated through the key
hooks.leave_request_no_overlap.refusals.OVERLAP.message) and the caller a409whosedeclaredCodeisOVERLAP.
Known limits — the hook does not cover these, so do not assume it does:
- It reads, then the write happens: two saves at the same moment can both pass.
- A recycle-bin restore runs no insert hook.
- An import run with automations off skips hooks.
- Rows of one bulk insert or bulk update do not see each other.
- A row with no start or no end is neither checked nor counted.
Hook Context
handler receives a HookContext with these fields:
ctx = {
id, // tracing id
object, // target object name
event, // e.g. 'beforeInsert' | 'afterUpdate'
input, // mutable input — record fields exposed flat (raw wrapper: input.data, input.options)
result, // mutable operation result (after* events)
previous, // record state before the operation (update/delete)
session, // { userId, organizationId, positions, accessToken, isSystem }
user, // { id, name, email } convenience shortcut — reserved for future use;
// not currently set by the engine, use session.userId instead
transaction, // active transaction handle, if any
ql, // ObjectQL engine reference
api, // scoped cross-object access: ctx.api.object('x')
}Best Practices
✅ DO:
- Use before hooks to enrich/normalize the incoming record
- Use after hooks for related-record side effects
- Use
ctx.api.object('x')for cross-object access so writes stay in scope - Handle errors gracefully
- Verify every field your hook writes exists on the target object(s) — the write-set lint catches the literal cases, but it is advisory, and computed keys, spreads and aliased input are invisible to it (see Hook & Action Bodies)
❌ DON'T:
- Query in loops
- Trigger unbounded cascades of writes
- Perform heavy/long-running work inline in a hook
- Mutate
ctx.resultin before hooks (it is only populated for after hooks) - Treat a blocking
after*hook as proof the write committed — it fires inside the unit of work, so an un-retractable external effect there can outlive a rollback (see above); anasync: trueone runs only after the commit
Related business logic
Hooks are one of several business-logic layers. Topics formerly covered on this page now live on their own pages:
- Validation rules → /docs/data-modeling/validation
- Formula logic → /docs/data-modeling/formulas
- Flows → /docs/automation/flows
- Approval nodes → /docs/automation/approvals