From 7967453f574cbded076797837b4de171ad7eea0d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 17:09:00 +0200 Subject: [PATCH] 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 --- docs/hooks.md | 18 +++++++++++++ src/index.ts | 2 +- src/modules/hooks/buildRevalidateHook.ts | 24 ++++++++++++++++- src/modules/hooks/index.ts | 3 ++- src/plugin.ts | 12 +++++++-- src/types.ts | 10 +++++++ test/revalidateGlobals.test.ts | 34 ++++++++++++++++++++++++ 7 files changed, 98 insertions(+), 5 deletions(-) create mode 100644 test/revalidateGlobals.test.ts diff --git a/docs/hooks.md b/docs/hooks.md index 9bae9d7..de1965c 100644 --- a/docs/hooks.md +++ b/docs/hooks.md @@ -42,6 +42,24 @@ brak `process.env.NEXT_RUNTIME`. Wcześniej Next rzucał `Invariant: static gene i seed padał. Celowe pominięcie (masowy import w aplikacji): `context: { disableRevalidate: true }` w wywołaniu Local API. +### Globale — buildGlobalRevalidateHook / `ipalKit({ revalidatePath })` + +Global (Site Settings, Cookie Settings, menu projektu) zasila layout **każdej** strony — logo, menu, +teksty zgody, ID analityki. Bez rewalidacji strony ISR trzymały stare wartości do końca okna +`revalidate`. Zapis globala → `revalidatePath('/', 'layout')` (cała strona). + +```ts +// payload.config.ts — globale pluginu (Site Settings, Site Integrations, Cookie Settings, Notifications) +import { revalidatePath } from 'next/cache' +ipalKit({ …, revalidatePath }) + +// własny global projektu (np. menu) +import { buildGlobalRevalidateHook } from '@intecion/ipal-kit' +hooks: { afterChange: [buildGlobalRevalidateHook({ revalidatePath })] } +``` + +Te same reguły co wyżej: bez `NEXT_RUNTIME` i z `context: { disableRevalidate: true }` nic nie robi. + --- ## setPublishedAtHook — auto-data publikacji diff --git a/src/index.ts b/src/index.ts index d905d80..b801ebf 100644 --- a/src/index.ts +++ b/src/index.ts @@ -112,7 +112,7 @@ export type { ContentHelpers, EntryJsonLdContext, PageJsonLdOptions, SiteShell } export { createContentHelpers } from './modules/frontend/index.js' // Healthcheck route (Coolify/Docker liveness with a real DB round-trip). export { createHealthRoute } from './modules/health/index.js' -export { buildCrossLocaleFieldSync, buildPreventDeleteSystemPage, buildRevalidateHook, buildValidateUniqueRole, setPublishedAtHook, trackSlugHistoryHook } from './modules/hooks/index.js' +export { buildCrossLocaleFieldSync, buildGlobalRevalidateHook, buildPreventDeleteSystemPage, buildRevalidateHook, buildValidateUniqueRole, setPublishedAtHook, trackSlugHistoryHook } from './modules/hooks/index.js' export type { I18nConfig, LocaleDefinition, LocalizedSlugs } from './modules/i18n/index.js' export { buildLocalizedPath, diff --git a/src/modules/hooks/buildRevalidateHook.ts b/src/modules/hooks/buildRevalidateHook.ts index 1a51f09..f3cad40 100644 --- a/src/modules/hooks/buildRevalidateHook.ts +++ b/src/modules/hooks/buildRevalidateHook.ts @@ -1,10 +1,12 @@ -import type { CollectionAfterChangeHook, CollectionAfterDeleteHook } from 'payload' +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 @@ -114,3 +116,23 @@ export function buildRevalidateHook({ 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 + } +} diff --git a/src/modules/hooks/index.ts b/src/modules/hooks/index.ts index 0766415..73e6e6f 100644 --- a/src/modules/hooks/index.ts +++ b/src/modules/hooks/index.ts @@ -3,7 +3,8 @@ export { normalizeFilenameHook } from '../media/index.js' export { buildAutoFillMetaHook, validateFaviconField } from '../seo/index.js' export { buildCrossLocaleFieldSync } from './buildCrossLocaleFieldSync.js' -export { buildRevalidateHook } from './buildRevalidateHook.js' +export { buildGlobalRevalidateHook, buildRevalidateHook } from './buildRevalidateHook.js' +export type { RevalidatePathFn } from './buildRevalidateHook.js' export { buildPreventDeleteSystemPage } from './preventDeleteSystemPage.js' export { setPublishedAtHook } from './setPublishedAt.js' diff --git a/src/plugin.ts b/src/plugin.ts index e0124a2..2aaea8f 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -17,6 +17,7 @@ import { buildFormsPlugin } from './modules/forms/formsPluginConfig.js' import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js' import { buildSystemPagesFields } from './modules/pages/index.js' import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo/index.js' +import { buildGlobalRevalidateHook } from './modules/hooks/buildRevalidateHook.js' import { buildIndexNowHook } from './modules/seo/indexNow.js' import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.js' @@ -229,8 +230,7 @@ export const ipalKit = (options: IpalOptions): Plugin => { : []), ] - config.globals = [ - ...(config.globals ?? []), + const pluginGlobals = [ buildSiteSettings({ additionalFields: options.siteSettingsFields, ...(options.pages ? { constructionFields: buildConstructionFields(options.pages.slug) } : {}), @@ -241,6 +241,14 @@ export const ipalKit = (options: IpalOptions): Plugin => { buildCookieSettings(), buildNotifications(), ] + // A global feeds every page's layout — revalidate the site on save. + const revalidateGlobal = options.revalidatePath ? buildGlobalRevalidateHook({ revalidatePath: options.revalidatePath }) : null + config.globals = [ + ...(config.globals ?? []), + ...(revalidateGlobal + ? pluginGlobals.map((g) => ({ ...g, hooks: { ...g.hooks, afterChange: [...(g.hooks?.afterChange ?? []), revalidateGlobal] } })) + : pluginGlobals), + ] config.endpoints = [...(config.endpoints ?? []), testEmailEndpoint] diff --git a/src/types.ts b/src/types.ts index b6ffb61..fe646dd 100644 --- a/src/types.ts +++ b/src/types.ts @@ -12,6 +12,7 @@ export type TotpPluginFactory = (options: { forceSetup: boolean totp: { issuer: string } }) => Plugin +import type { RevalidatePathFn } from './modules/hooks/buildRevalidateHook.js' import type { AccessOption } from './modules/access/types.js' import type { ContentOption } from './modules/content/types.js' import type { FormsOption } from './modules/forms/types.js' @@ -88,6 +89,15 @@ export type IpalOptions = { */ pages?: PagesOption + /** + * next/cache `revalidatePath`, INJECTED (the plugin never imports next/cache). + * When given, saving any of the plugin's globals (Site Settings, Site + * Integrations, Cookie Settings, Notifications) revalidates the whole site + * layout, so logo, menu, consent texts and analytics IDs change at once + * instead of after the ISR window. See buildGlobalRevalidateHook. + */ + revalidatePath?: RevalidatePathFn + /** * SEO — adds meta fields to chosen collections (via @payloadcms/plugin-seo) * and enables locale-aware metadata helpers. diff --git a/test/revalidateGlobals.test.ts b/test/revalidateGlobals.test.ts new file mode 100644 index 0000000..f1ff0d9 --- /dev/null +++ b/test/revalidateGlobals.test.ts @@ -0,0 +1,34 @@ +import type { Config, GlobalConfig } from 'payload' + +import { afterEach, describe, expect, test, vi } from 'vitest' + +import { buildGlobalRevalidateHook } from '../src/modules/hooks/buildRevalidateHook.js' +import { ipalKit } from '../src/plugin.js' + +const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } +const run = (g: GlobalConfig | undefined, context: object = {}) => + g?.hooks?.afterChange?.forEach((h) => h({ context, doc: {}, global: g, previousDoc: {}, req: {} } as never)) + +describe('globals revalidate the site layout on save', () => { + afterEach(() => vi.unstubAllEnvs()) + + test('ipalKit({ revalidatePath }) wires every plugin global', async () => { + vi.stubEnv('NEXT_RUNTIME', 'nodejs') + const revalidatePath = vi.fn() + const config = await ipalKit({ i18n, revalidatePath, twoFactor: false })({ collections: [], secret: 'x' } as unknown as Config) + for (const slug of ['site-settings', 'site-integrations', 'cookie-settings', 'notifications']) { + revalidatePath.mockClear() + run(config.globals?.find((g) => g.slug === slug)) + expect(revalidatePath, slug).toHaveBeenCalledWith('/', 'layout') + } + }) + + test('outside a Next server, or with disableRevalidate, nothing happens', () => { + const revalidatePath = vi.fn() + const hook = buildGlobalRevalidateHook({ revalidatePath }) + hook({ context: {}, doc: {} } as never) + vi.stubEnv('NEXT_RUNTIME', 'nodejs') + hook({ context: { disableRevalidate: true }, doc: {} } as never) + expect(revalidatePath).not.toHaveBeenCalled() + }) +})