Files
ipal-kit/docs/hooks.md
T
Radosław SmolińskiandClaude Fable 5.2 b91984fbcd IAPL rename: docs, agent guide, skills, reference site and starter on the new names; changelog draft
- docs, AGENT.md, the 16 skills, PROGRAMISTA and README use the preferred names (scripted, same list of forms);
  past CHANGELOG entries and the proposals in docs/dev are not rewritten
- AGENT.md: 'Names: IAPL and ipal-kit' — old name, new name, state in 1.x; what is not renamed; storageNames
- iapl-upgrade '→ 1.17.0', PROGRAMISTA §6 item 72, CHANGELOG 1.17.0 (draft): nothing required
- env.md, doctor.md (legacy-names, storage-names), stats.md, security.md, project-starter.md, iapl-reference, iapl-setup
- skill scripts read ipal-audit-skip and IPAL_IP_HEADER too; audit rule ids stay what they were
- reference site: iapl(), iapl-doctor.json, iapl-* skills, storageNames: 'iapl'; INDEX.md regenerated

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 17:36:09 +01:00

307 lines
14 KiB
Markdown

# Plugin hooks — automating page work
The plugin ships hooks that take repetitive work off projects. You wire them
into collections; they run automatically. All are ready to use (import from the plugin).
Related: [pages.md](./pages.md), [seo.md](./seo.md), [the developer guide (PROGRAMISTA.md) §5](./dev/PROGRAMISTA.md).
---
## buildRevalidateHook — ISR refreshed on save (THE MOST IMPORTANT)
Without it ISR has a catch: the editor saves a page and WAITS for revalidate (up to
an hour). With it, they save and see the change AT ONCE. This is what makes ISR
usable for a CMS.
```ts
// Pages collection — from a project file that CAN import next/cache
import { revalidatePath } from 'next/cache'
import { buildRevalidateHook } from '@intecion/ipal-kit'
import { i18nConfig } from '@/i18n.config'
const { afterChange, afterDelete } = buildRevalidateHook({
revalidatePath, // injected — the plugin does NOT import next/cache
config: i18nConfig,
})
export const Pages: CollectionConfig = {
slug: 'pages',
hooks: { afterChange: [afterChange], afterDelete: [afterDelete] },
// ...
}
```
**Why revalidatePath is injected:** the plugin does not import `next/cache` (that
would crash Payload during generate:importmap / in plain Node). The project passes it.
Options: `revalidatePath` (required), `config` (required), `homeSlug` (default `'home'`,
a string or a per-locale map — the home page slug, so the root `/pl` is revalidated; if your
home page has a different slug, pass it, otherwise the root is not refreshed).
What it does: for each locale in `config` it builds the path with `buildLocalizedPath` from the
document's slug and calls `revalidatePath`; when the slug changes, the old path too; `afterDelete` —
the path of the deleted document.
Limits (code state, `src/modules/hooks/buildRevalidateHook.ts`):
- **Collections only** — these are collection `afterChange`/`afterDelete` hooks. Globals are
handled by `buildGlobalRevalidateHook` / `iapl({ revalidatePath })` — see below.
- The slug in the hook is usually a string in the saved locale, so the same slug goes into the path
of every locale (`/pl/o-nas`, `/en/o-nas`); the real address in another locale (`/en/about`) is not
refreshed. A change to a non-localized field (e.g. an image) stays stale in other locales until
`revalidate` runs out.
- No archive prefix support: a `posts` entry gives `/pl/moj-post`, not `/pl/artykuly/moj-post`;
the archive page (listing) is not refreshed after an entry changes. For `content` collections
add your own hook (`revalidatePath('/pl/artykuly', 'layout')` or `buildEntryPath`).
- Sitemap, llms.txt and MCP have their own cache/`dynamic` — the hook does not touch them.
**Outside the Next server** (1.11.1) the hook does nothing: `pnpm payload run`, seeding via `tsx`,
migrations — there is no `process.env.NEXT_RUNTIME`. Before, Next threw `Invariant: static generation store missing`
and the seed failed. Deliberate skip (bulk import in the app): `context: { disableRevalidate: true }`
in the Local API call.
### Globals — buildGlobalRevalidateHook / `iapl({ revalidatePath })`
A global (Site settings, Cookie banner, the project's menu) feeds the layout of **every** page — logo, menu,
consent texts, analytics IDs. Without revalidation, ISR pages kept the old values until the end of the
`revalidate` window. Saving a global → `revalidatePath('/', 'layout')` (the whole site).
```ts
// payload.config.ts — the plugin's globals (Site settings, Site integrations, Cookie banner, Notifications)
import { revalidatePath } from 'next/cache'
iapl({ …, revalidatePath })
// the project's own global (e.g. a menu)
import { buildGlobalRevalidateHook } from '@intecion/ipal-kit'
hooks: { afterChange: [buildGlobalRevalidateHook({ revalidatePath })] }
```
- With `revalidatePath` passed to `iapl()`, the plugin appends the hook itself to `afterChange` of
`site-settings`, `site-integrations`, `cookie-settings` and `notifications`
(`src/plugin.ts`). Without the option, the plugin's globals are not revalidated.
- The project's own globals (Header/Footer menu etc.) need the hook wired by hand, as above.
- Same rules as above: without `NEXT_RUNTIME` and with `context: { disableRevalidate: true }` it does nothing.
- Need something more precise (e.g. `revalidateTag('header')`) or want to drop the plugin's hook? Use
`globalOverrides` (see "Turn off, override, extend" below) — an object appends your hooks after the
plugin's, a function gets the whole global and returns the one to use.
---
## setPublishedAtHook — automatic publish date
Sets `publishedAt` to now on the first publish (if empty). The editor
does not type the date by hand; the date is exact for Article JSON-LD and the sitemap.
```ts
import { setPublishedAtHook } from '@intecion/ipal-kit'
// a collection with drafts (blog, articles):
hooks: { beforeChange: [setPublishedAtHook] }
```
It sets the date only on the switch to published; it does not overwrite an existing date
(the editor can backdate by hand).
---
## buildPreventDeleteSystemPage — protecting system pages
Blocks deleting a page assigned to a role (homepage, privacyPolicy,
cookiePolicy, termsOfService). The editor cannot delete the privacy policy
or the home page by accident → routing and compliance links do not break.
```ts
import { buildPreventDeleteSystemPage } from '@intecion/ipal-kit'
hooks: { beforeDelete: [buildPreventDeleteSystemPage({ settingsSlug: 'site-settings' })] }
```
It reads Site settings in the same `req` (the delete transaction).
To delete — first detach the role in Site settings (a deliberate decision).
Options: `settingsSlug` (`'site-settings'`), `roleFields` (default `['homepage',
'privacyPolicy', 'cookiePolicy', 'termsOfService']` — **without `notFound`**; the 404 page and
`content` archive pages can be deleted unless you add them, e.g. `'postsArchive'`).
An error reading SiteSettings → the delete goes through.
---
## buildValidateUniqueRole — one page = one role
Prevents assigning the same page to two system roles (e.g. homepage AND
privacyPolicy at once → ambiguous routing).
The plugin builds the role fields in SiteSettings and **does not add this hook to them** — it does
not work on its own. Wire it into your own role fields (or into the plugin's fields through
`globalOverrides['site-settings']` as a function that maps the fields). Do not add `notFound` to `siblingFields`
if the 404 page should be allowed to be the home page.
```ts
import { buildValidateUniqueRole } from '@intecion/ipal-kit'
// on a role field:
{
name: 'privacyPolicy',
type: 'relationship',
relationTo: 'pages',
hooks: { beforeValidate: [buildValidateUniqueRole({
siblingFields: ['homepage', 'cookiePolicy', 'termsOfService'],
})] },
}
```
---
## trackSlugHistoryHook — automatic 308 (permanent) redirect on slug change
When the slug changes, it appends the OLD slug to the `slugHistory` field (no duplicates; the field name
is fixed — `slugHistory` with a `slug` subfield). You must add the field to the collection yourself. The project reads it
and does a permanent redirect (308, for Google the same as 301) from the old URL to the new one → an address change does not give a 404 (a real SEO loss
found in the audit).
```ts
import { trackSlugHistoryHook } from '@intecion/ipal-kit'
export const Pages: CollectionConfig = {
fields: [
// ...
{ name: 'slugHistory', type: 'array', admin: { readOnly: true },
fields: [{ name: 'slug', type: 'text' }] },
],
hooks: { beforeChange: [trackSlugHistoryHook] },
}
```
Reading this history is done by `resolveRedirect` (content module) — do NOT write your own
lookup. In the catch-all, when `resolveRoute` finds no page:
```tsx
import { resolveRoute, resolveRedirect } from '@intecion/ipal-kit'
import { permanentRedirect, notFound } from 'next/navigation'
const route = await resolveRoute({ /* … */ })
if (!route) {
const dest = await resolveRedirect({
payload, locale, segments: slug, config: i18nConfig, homeSlug,
collections: [{ slug: 'pages' }],
})
if (dest) permanentRedirect(dest) // HTTP 308 — for SEO equivalent to 301
notFound()
}
```
The plugin computes the target, the project calls `permanentRedirect` (the plugin does not import
`next/navigation`). A collection without a `slugHistory` field is skipped safely
(try/catch — the same class of error as `_status`). Multi-segment slugs
(`uslugi/biznesowe`) work; archive entries (`/artykuly/<entry>`) not yet.
Details: [content.md](./content.md).
---
## buildCrossLocaleFieldSync — shared fields in localized blocks
Payload localizes the whole `blocks`/`array` field at once — you cannot mark a
single subfield (an image) as non-localized. Result: the editor picks
images in Polish and must repeat the choice in every language. This hook copies
the given fields (images, icons) from the edited locale to the others.
```ts
import { buildCrossLocaleFieldSync } from '@intecion/ipal-kit'
import { i18nConfig } from '@/i18n.config'
hooks: {
afterChange: [
buildCrossLocaleFieldSync({ config: i18nConfig, collection: 'pages', fields: ['image'] }),
],
}
```
- **Locale list from `config`** — NEVER hardcode `['pl','en',…]` (A0:
adding a language in the admin panel works without a code change).
- **Rows matched by `id`**, positional fallback only when `blockType`
matches — it will not put an image into a block of another type.
- **Many fields:** `fields: ['image', 'backgroundImage', 'icon']`.
- **Filled fields only** — clearing an image in one language does not clear
it in the others (conservative).
- The `_ipalSyncingCrossLocale` guard breaks the `afterChange`→`update` loop.
- **Inside the save transaction:** reading and writing the other locales go through `req` (Postgres/Mongo — a rollback
also covers the sync); `req.locale` / `req.fallbackLocale` are restored after the hook to the values from the
save, so the API response stays in the editor's language.
Parameters: `config`, `collection`, `fields` (required), `arrayField` (default `'layout'`),
`guardFlag` (default `'_ipalSyncingCrossLocale'`). Only top-level fields of a row are copied
(no nested arrays); a locale without any rows is skipped.
A sync error is logged; the save does not fail.
---
## buildFillEmptyLocalesGlobalHook / buildFillEmptyLocalesCollectionHook — text into empty languages
The text counterpart of `buildCrossLocaleFieldSync`: text saved in one language goes to every
language where that field is still empty; a language with its own text is never overwritten. The
plugin adds it to the cookie list and the cookie review (`iapl({ fillEmptyLocales })`, consent.md).
On your own global or collection:
```ts
import { buildFillEmptyLocalesGlobalHook } from '@intecion/ipal-kit'
hooks: {
afterChange: [buildFillEmptyLocalesGlobalHook({ global: 'footer', fields: ['tagline', 'links.label'] })],
}
```
Fields: `'field'` or `'arrayField.subField'` (rows matched by their id). The collection variant takes
`{ collection, fields }`. It skips its own writes (`context.ipalFillLocales`) and the cookie scanner's,
puts `req.locale` back afterwards, and logs instead of failing the save. Core function:
`fillEmptyLocales`; `withFillLocales(kind, config, fields)` adds the hook to a config.
---
## buildNoindexField — checkbox → meta.noindex (a field, not a hook)
A sidebar `noindex` checkbox kept in sync with `meta.noindex` (which the sitemap and
metadata read), without `any`. It is a field factory — wire it into `fields`, not `hooks`:
```ts
import { buildNoindexField } from '@intecion/ipal-kit'
fields: [ /* … */ buildNoindexField() ]
```
Options: `name`, `label`, `description`, `metaPath` (default `'meta.noindex'`),
`overrides`. Details: [seo.md](./seo.md).
---
## Hook ORDER (important)
In one collection, hooks of the same phase run in order. A typical Media:
```ts
hooks: {
beforeOperation: [normalizeFilenameHook], // clean file names
afterChange: [afterChange], // revalidate
afterDelete: [afterDelete],
}
```
A typical Pages:
```ts
hooks: {
beforeChange: [setPublishedAtHook, trackSlugHistoryHook],
beforeDelete: [buildPreventDeleteSystemPage(...)],
afterChange: [afterChange, buildCrossLocaleFieldSync({ config, collection: 'pages', fields: ['image'] })],
afterDelete: [afterDelete],
}
// field: buildNoindexField() in `fields`
```
Which hooks to wire depends on the collection — not every one needs all of them (blog:
setPublishedAt; everything with a URL: revalidate + slugHistory; Pages: + preventDelete).
---
## Turn off, override, extend
- The plugin does not wire these collection hooks itself (exceptions: `seo` → meta auto-fill, `indexNow` → the IndexNow hook) — you add each one in the project's collection, so turning one off = not adding it.
- Global revalidation: the plugin adds `buildGlobalRevalidateHook` to its own globals only when you pass `iapl({ revalidatePath })`; leave the option out to turn it off.
- `globalOverrides` (`iapl({ globalOverrides: { 'site-settings': …, 'site-integrations': …, 'cookie-settings': …, notifications: … } })`): an object merges over the plugin's global — `access`, `admin` and `hooks` key by key (your access rules win, your hooks run after the plugin's), any other key replaces the plugin's value; a function gets the plugin's global and returns the one to use (full control, e.g. drop the plugin's revalidate hook, add `buildValidateUniqueRole` to the role fields, or use `revalidateTag`).
- Skip revalidation per call: `context: { disableRevalidate: true }`.
- Configurable: `homeSlug` (revalidate), `settingsSlug`/`roleFields` (preventDelete), `siblingFields` (unique role), `arrayField`/`guardFlag`/`fields` (cross-locale sync).
- Fixed: the field name `slugHistory` in `trackSlugHistoryHook` and `publishedAt`/`_status` in `setPublishedAtHook` — other names need your own hook.
- The project's own globals and archive prefixes: revalidate with your own hook (`buildGlobalRevalidateHook` / `revalidatePath(…, 'layout')`, above).