# payload-hooks — Agent usage Configure a coding agent for @nexload-sdk/payload-hooks. **Topic:** agents **Package:** `@nexload-sdk/payload-hooks` v3.1.0 **Canonical page:** https://gecut.github.io/nexload-sdk/packages/payload-hooks/agents/ ## Install matching skills Use the hooks skill for after-commit side effects and standalone audit logging, the preset skill for the composed setup, and collection design for Payload boundaries. ### payload-hooks [Trigger](https://github.com/gecut/nexload-sdk/blob/main/skills/payload-hooks/SKILL.md) ```text Use when adding, reviewing, or debugging transaction-safe side effects or audit logging in Payload CMS with @nexload-sdk/payload-hooks: afterCommitPlugin, runAfterCommit(req, key, fn), isAfterCommitInstalled, or standalone auditPlugin. Decides where a side effect (SMS, email, queue job, webhook, cache call) may run relative to the database commit, how to pick callback keys, what happens on rollback, and how audit entries relate to transactions. Do not use for the composed preset options (use payload-preset), cache revalidation rules (use payload-revalidate), log event naming and levels (use logger), or custom operation endpoints (use payload-operations). ``` ```bash npx skills add gecut/nexload-sdk --skill payload-hooks ``` ### payload-preset [Trigger](https://github.com/gecut/nexload-sdk/blob/main/skills/payload-preset/SKILL.md) ```text Use when configuring or reviewing Payload CMS configuration with @nexload-sdk/payload-preset, composing Persian admin defaults, logger bridge, after-commit callbacks (afterCommit option), field hooks, or collection audit logging with auditPlugin. Decides between preset and standalone plugins, validates options and defaults, verifies plugin order and non-interference with collection fields, or migrates from deprecated logOperation. Do not use for field schema definitions (use payload-schema) or single field customizations (use payload-fields). ``` ```bash npx skills add gecut/nexload-sdk --skill payload-preset ``` ### payload-collection-design [Trigger](https://github.com/gecut/nexload-sdk/blob/main/skills/payload/collection-design/SKILL.md) ```text Design, name, review, and refactor Payload CMS collections and PostgreSQL-backed data relationships. Use whenever choosing embedded fields versus Globals or collections, modeling cardinality and ownership, defining junction collections, naming resources and fields, selecting indexes and constraints, setting deletion behavior, preserving historical snapshots, or auditing a Payload schema for data-model correctness. ``` ```bash npx skills add gecut/nexload-sdk --skill payload-collection-design ``` ## Project AGENTS.md ```markdown For @nexload-sdk/payload-hooks, load payload-hooks when its trigger matches. Read the package bundle and check public exports against the installed version before editing. ``` ## Package context [Scoped Markdown bundle](/nexload-sdk/packages/payload-hooks/llms.txt). ## Prompts ```text Send a notification only after the order transaction commits, and audit writes to an explicit collection. Use @nexload-sdk/payload-hooks and the payload-hooks skill. Inspect the installed version and show a minimal typed example for my project. ``` ```text Review my @nexload-sdk/payload-hooks integration against the optimization page. Identify the relevant source for each finding and one test for the highest-risk behavior. ``` --- # API Reference & Compatibility Public audit plugin and legacy hook exports. **Topic:** api **Package:** `@nexload-sdk/payload-hooks` v3.1.0 **Canonical page:** https://gecut.github.io/nexload-sdk/packages/payload-hooks/api/ The inventory is generated from the package source exports. ## Functions ### `afterCommitPlugin` ```ts afterCommitPlugin(options?: AfterCommitPluginOptions) => Plugin ``` **Exported from:** `@nexload-sdk/payload-hooks` Public function exported by @nexload-sdk/payload-hooks. [Source](https://github.com/gecut/nexload-sdk/blob/main/packages/payload-hooks/src/after-commit.ts#L158) ### `auditPlugin` ```ts auditPlugin(options?: AuditPluginOptions) => Plugin ``` **Exported from:** `@nexload-sdk/payload-hooks` Public function exported by @nexload-sdk/payload-hooks. [Source](https://github.com/gecut/nexload-sdk/blob/main/packages/payload-hooks/src/audit-plugin.ts#L326) ### `isAfterCommitInstalled` ```ts isAfterCommitInstalled(payload: Payload) => boolean ``` **Exported from:** `@nexload-sdk/payload-hooks` Returns true once `afterCommitPlugin()` has run `onInit` for this Payload instance. [Source](https://github.com/gecut/nexload-sdk/blob/main/packages/payload-hooks/src/after-commit.ts#L171) ### `runAfterCommit` ```ts runAfterCommit(req: PayloadRequest, key: string, fn: AfterCommitCallback) => void ``` **Exported from:** `@nexload-sdk/payload-hooks` Public function exported by @nexload-sdk/payload-hooks. [Source](https://github.com/gecut/nexload-sdk/blob/main/packages/payload-hooks/src/after-commit.ts#L175) ## Constants ### `AUDIT_PLUGIN_ORDER` ```ts AUDIT_PLUGIN_ORDER: 1000 ``` **Exported from:** `@nexload-sdk/payload-hooks` Public constant exported by @nexload-sdk/payload-hooks. [Source](https://github.com/gecut/nexload-sdk/blob/main/packages/payload-hooks/src/audit-plugin.ts#L25) ### `logOperation` ```ts logOperation>(hookType: THookType) => TReturn ``` **Exported from:** `@nexload-sdk/payload-hooks` Public constant exported by @nexload-sdk/payload-hooks. [Source](https://github.com/gecut/nexload-sdk/blob/main/packages/payload-hooks/src/log-operation.ts#L23) ## Types ### `AfterCommitCallback` ```ts type AfterCommitCallback = () => void | Promise; ``` **Exported from:** `@nexload-sdk/payload-hooks` Public type exported by @nexload-sdk/payload-hooks. [Source](https://github.com/gecut/nexload-sdk/blob/main/packages/payload-hooks/src/after-commit.ts#L7) ### `AfterCommitPluginOptions` ```ts type AfterCommitPluginOptions = { logger?: Pick }; ``` **Exported from:** `@nexload-sdk/payload-hooks` Public type exported by @nexload-sdk/payload-hooks. [Source](https://github.com/gecut/nexload-sdk/blob/main/packages/payload-hooks/src/after-commit.ts#L8) ### `AuditOperation` ```ts type AuditOperation = "create" | "update" | "delete" | "read" | "auth"; ``` **Exported from:** `@nexload-sdk/payload-hooks` Public type exported by @nexload-sdk/payload-hooks. [Source](https://github.com/gecut/nexload-sdk/blob/main/packages/payload-hooks/src/audit-plugin.ts#L16) ### `AuditPluginOptions` ```ts type AuditPluginOptions = { collections?: "all" | string[]; exclude?: string[]; operations?: AuditOperation[]; logger?: Pick; }; ``` **Exported from:** `@nexload-sdk/payload-hooks` Public type exported by @nexload-sdk/payload-hooks. [Source](https://github.com/gecut/nexload-sdk/blob/main/packages/payload-hooks/src/audit-plugin.ts#L18) ## Exported Factories Summary `auditPlugin(options?: AuditPluginOptions): Plugin` attaches audit hooks. `AUDIT_PLUGIN_ORDER` is `1000`. `AuditOperation` is `"create" | "update" | "delete" | "read" | "auth"`. `afterCommitPlugin(options?: AfterCommitPluginOptions): Plugin` wraps transaction lifecycle for `runAfterCommit(req: PayloadRequest, key: string, fn: AfterCommitCallback): void`. `isAfterCommitInstalled(payload): boolean` returns `true` after `afterCommitPlugin()` ran `onInit` for that Payload instance; use it to choose commit-exact behaviour without a throw. `logOperation` is deprecated; see the [migration guide](../guides/). --- # Production Guides & Recipes Audit options, events, privacy, and migration. **Topic:** guides **Package:** `@nexload-sdk/payload-hooks` v3.1.0 **Canonical page:** https://gecut.github.io/nexload-sdk/packages/payload-hooks/guides/ ## Audit options | Option | Default | Behavior | | --- | --- | --- | | `collections` | `"all"` | All collections or an array of slugs. | | `exclude` | `[]` | Slugs to skip. Unknown requested or excluded slugs throw at config time. | | `operations` | `["create", "update", "delete", "auth"]` | Enabled operations; add `"read"` to audit reads. | | `logger` | SDK default logger | Custom logger with an `info` method. | The plugin runs at order 1000 and appends hooks after existing hooks. Writes log once per document. Reads are off by default; when enabled, each request produces one list summary or single-read event. Auth auditing is on by default for auth collections; failed logins are not logged. Logging failures do not interrupt operations. Events contain identifiers and counts, never document bodies, emails, tokens, or other credentials. ## Events * `payload.document.created` * `payload.document.updated` * `payload.document.deleted` * `payload.documents.listed` * `payload.document.read` * `payload.auth.logged_in` * `payload.auth.password_reset_requested` * `payload.auth.password_reset` Write event IDs may be absent. List events include a count rather than document contents or IDs. ## Boundaries Payload creates its implicit default `users` collection after plugins run. Declare the auth collection explicitly to audit its auth and write events. ### Audit entries and transactions With `afterCommitPlugin()` installed (`nexloadPreset()` installs it by default), `payload.document.created`, `payload.document.updated` and `payload.document.deleted` are written after the transaction commits. A write that rolls back produces no entry. Without the plugin, write hooks emit events before the commit, so a later rollback can leave an event for a change that did not persist. A request with no transaction writes its entry at once. Read and auth entries are always written at once. ## Migrate from `logOperation` `logOperation` is deprecated. Remove per-collection hooks and register the plugin once: ```ts // Before: hooks: { afterChange: [logOperation("afterChange")] } import { auditPlugin } from "@nexload-sdk/payload-hooks"; const plugins = [auditPlugin()]; ``` The preset also includes `auditPlugin` by default; do not register it twice. See [Payload Preset](/nexload-sdk/packages/payload-preset/). ## Run side effects after commit Register `afterCommitPlugin()` once in your Payload config, then call `runAfterCommit(req, key, fn)` from any hook or endpoint that holds `req`: ```ts import { afterCommitPlugin, runAfterCommit } from "@nexload-sdk/payload-hooks"; const plugins = [afterCommitPlugin()]; // Inside a collection hook: afterChange: [ ({ doc, req }) => { runAfterCommit(req, `sms:order:${doc.id}`, () => sms.enqueue(orderShipped(doc)), ); }, ]; ``` Keep callbacks short (enqueue work rather than sending it directly), because `commitTransaction` awaits each callback sequentially before resolving. * **Plugin required:** Calling `runAfterCommit` without `afterCommitPlugin()` installed throws `Error("[payload-hooks] runAfterCommit requires afterCommitPlugin()")`. * **Transaction lifecycle:** Callbacks wait for `commitTransaction`, are deduplicated by `key` within a single transaction (last wins, first position kept), and are dropped on `rollbackTransaction`, commit failure, rejected `transactionID` promise, or `db.destroy()`. Registration order across mixed `Promise` and value transaction IDs follows resolution order. * **No transaction:** Falsy `req.transactionID` (or a promise resolving to a falsy value) runs `fn` on the next microtask via the safe runner. Because there is no transaction to wait on, register `runAfterCommit` only after the write succeeds (`afterChange`/`afterDelete` or after the Local API call returns), never in `beforeChange`/`beforeValidate`. * **Nested calls during flush:** Nested registrations of new keys made with the same `req` join the active flush in order (not-yet-started keys are replaced in place) and are awaited before `commitTransaction` resolves; re-registering a key that already started during the same flush is ignored. Use the original `req` inside a callback only to register more callbacks; for new writes create a fresh request (or omit `req`), because `req.transactionID` still names the committed transaction and a write that reuses it is not rolled back on failure. * **Registration during commit:** A registration made while the adapter is still committing joins the same queue; it runs if the commit succeeds and is dropped if it fails. * **Destroy and repeated installs:** `db.destroy()` clears pending callbacks and stops a flush in progress after its current callback. Listing the plugin twice installs it once; the first `logger` wins. * **Error isolation:** Callback errors are caught and logged at `error` level (`payload-hooks.after_commit.callback_failed` with `key` and `err`) without failing the commit or stopping later callbacks. * **Caveats:** Callbacks live in memory (a crash between commit and execution loses them; use an outbox for durability), and Payload's Drizzle adapters (3.86) swallow a failed `COMMIT` so callbacks still run in that rare case. --- # Overview & Quick Start Audit Payload collection operations with structured log events. **Topic:** overview **Package:** `@nexload-sdk/payload-hooks` v3.1.0 **Canonical page:** https://gecut.github.io/nexload-sdk/packages/payload-hooks/ **Package:** `@nexload-sdk/payload-hooks` **Workspace version:** `3.1.0` Effortless, type-safe logging for Payload CMS collection operations. [npm](https://www.npmjs.com/package/@nexload-sdk/payload-hooks) · [Source](https://github.com/gecut/nexload-sdk/tree/main/packages/payload-hooks) `auditPlugin` attaches log-only collection hooks. It stores no audit records and does not change collection fields. ## Installation ```bash pnpm add @nexload-sdk/payload-hooks payload ``` ## Quick Start ```ts import { auditPlugin } from "@nexload-sdk/payload-hooks"; const plugins = [auditPlugin({ operations: ["create", "update", "delete", "read", "auth"] })]; ``` Reads are off by default; auth is on for auth collections. See [guides](./guides/) for event names, options, and transaction caveats. Payload `>=3.85.0 <4.0.0` is a peer dependency; the hooks run in Node.js Payload configuration. ## Next steps [Optimization](./optimization/) [Agent usage](./agents/) --- # payload-hooks — Optimization Production choices for @nexload-sdk/payload-hooks. **Topic:** optimization **Package:** `@nexload-sdk/payload-hooks` v3.1.0 **Canonical page:** https://gecut.github.io/nexload-sdk/packages/payload-hooks/optimization/ ## Declare the auth collection Declare an auth collection in the config to include it in auditing. Payload creates its implicit users collection after plugins run. ## Interpret write events in context Write events from afterChange and afterDelete run before the database transaction commits. ## Avoid read auditing by default Read auditing is off by default. When enabled, `find` logs once per request with a count, while `findByID` logs the document ID. ## Treat audit output as logs The plugin does not persist database audit records. Authentication auditing covers successful logins and password resets, not failed logins. ## Sources [Package guidance](https://github.com/gecut/nexload-sdk/blob/main/packages/payload-hooks/README.md) · [Implementation](https://github.com/gecut/nexload-sdk/blob/main/packages/payload-hooks/src/index.ts).