Files
ipal-kit/src/modules/hooks/buildRevalidateHook.ts
T
Radosław SmolińskiandClaude Opus 5.5 7967453f57 Revalidate the site layout when a global is saved
buildGlobalRevalidateHook + ipalKit({ revalidatePath }) wires it into the
plugin's globals; menus, consent texts and analytics IDs no longer stay
stale for the whole ISR window.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:09:00 +02:00

139 lines
5.4 KiB
TypeScript

import type { CollectionAfterChangeHook, CollectionAfterDeleteHook, GlobalAfterChangeHook } from 'payload'
import type { I18nConfig } from '../i18n/index.js'
import { buildLocalizedPath, getLocaleCodes } from '../i18n/index.js'
type RevalidateFn = (path: string) => void
/** next/cache revalidatePath — the `type` argument is used for 'layout'. */
export type RevalidatePathFn = (path: string, type?: 'layout' | 'page') => void
type BuildRevalidateHookArgs = {
config: I18nConfig
/** Home slug (string or per-locale map) — home revalidates the root. */
homeSlug?: Record<string, string> | string
/**
* next/cache revalidatePath, INJECTED by the project. The plugin never imports
* next/cache itself — that would crash when Payload runs as plain Node
* (generate:importmap). The project passes it: `revalidatePath` from 'next/cache'.
*/
revalidatePath: RevalidateFn
}
type DocWithSlug = { slug?: unknown }
/**
* Revalidation only makes sense inside a running Next server. Outside it
* (`payload run`, seeds via tsx, migrations) next/cache throws "Invariant: static
* generation store missing". `context.disableRevalidate` (Payload templates'
* convention) skips it on purpose, e.g. in a bulk import.
*/
function shouldRevalidate(context: unknown): boolean {
if (!process.env.NEXT_RUNTIME) {return false}
return !(context && typeof context === 'object' && (context as { disableRevalidate?: unknown }).disableRevalidate)
}
/** Resolve a doc's path in one locale (root for home). Null if no slug there. */
function pathForLocale(
doc: DocWithSlug,
locale: string,
config: I18nConfig,
homeSlug?: Record<string, string> | string,
): null | string {
const slugField = doc.slug
const slug =
typeof slugField === 'string'
? slugField
: slugField && typeof slugField === 'object'
? ((slugField as Record<string, unknown>)[locale] as string | undefined)
: undefined
if (!slug) {return null}
return buildLocalizedPath({ config, homeSlug, locale, slugs: { [locale]: slug } }) ?? null
}
/**
* Builds afterChange + afterDelete hooks that revalidate a page's ISR cache when
* an editor saves or deletes it — so changes appear immediately instead of
* waiting for the revalidate window. Without this, ISR means editors wait; with
* it, ISR is usable for a CMS.
*
* Handles every locale, the root (home), AND a changed slug (revalidates both the
* old and new path so neither goes stale). revalidatePath is injected — the
* plugin never imports next/cache (safe under generate:importmap / plain Node).
* Outside a Next server (no NEXT_RUNTIME: `payload run`, seeds, migrations) and
* with `context: { disableRevalidate: true }` the hooks do nothing.
*
* // in your Media/Pages collection config, from a project file that CAN import next/cache:
* import { revalidatePath } from 'next/cache'
* import { buildRevalidateHook } from '@intecion/ipal-kit'
* const { afterChange, afterDelete } = buildRevalidateHook({ revalidatePath, config: i18nConfig })
* // hooks: { afterChange: [afterChange], afterDelete: [afterDelete] }
*/
export function buildRevalidateHook({
config,
homeSlug,
revalidatePath,
}: BuildRevalidateHookArgs): {
afterChange: CollectionAfterChangeHook
afterDelete: CollectionAfterDeleteHook
} {
const locales = getLocaleCodes(config)
const afterChange: CollectionAfterChangeHook = ({ context, doc, previousDoc }) => {
if (!shouldRevalidate(context)) {return doc}
const seen = new Set<string>()
for (const locale of locales) {
// New path.
const newPath = pathForLocale(doc as DocWithSlug, locale, config, homeSlug)
if (newPath && !seen.has(newPath)) {
revalidatePath(newPath)
seen.add(newPath)
}
// Old path, if the slug changed — so the old URL doesn't serve stale content.
if (previousDoc) {
const oldPath = pathForLocale(previousDoc as DocWithSlug, locale, config, homeSlug)
if (oldPath && oldPath !== newPath && !seen.has(oldPath)) {
revalidatePath(oldPath)
seen.add(oldPath)
}
}
}
return doc
}
const afterDelete: CollectionAfterDeleteHook = ({ context, doc }) => {
if (!shouldRevalidate(context)) {return doc}
const seen = new Set<string>()
for (const locale of locales) {
const path = pathForLocale(doc as DocWithSlug, locale, config, homeSlug)
if (path && !seen.has(path)) {
revalidatePath(path)
seen.add(path)
}
}
return doc
}
return { afterChange, afterDelete }
}
/**
* afterChange for a GLOBAL (Site Settings, Cookie Settings, a menu…): a global
* feeds the layout of every page — logo, menu, consent texts, analytics IDs —
* so a save revalidates the whole site (`revalidatePath('/', 'layout')`).
* Without it, every ISR page kept the old values until its revalidate window
* ran out. Same rules as buildRevalidateHook: injected revalidatePath, no-op
* outside a Next server or with `context: { disableRevalidate: true }`.
*
* import { revalidatePath } from 'next/cache'
* hooks: { afterChange: [buildGlobalRevalidateHook({ revalidatePath })] }
*
* ipalKit({ revalidatePath }) attaches it to the plugin's own globals.
*/
export function buildGlobalRevalidateHook({ revalidatePath }: { revalidatePath: RevalidatePathFn }): GlobalAfterChangeHook {
return ({ context, doc }) => {
if (shouldRevalidate(context)) {revalidatePath('/', 'layout')}
return doc
}
}