ggaidelevicius

payload isr

by ggaidelevicius
Publishing workflow
v3
^3.37.0
MIT

Overview

Summary generated from the README

Registers Payload afterOperation and afterChange hooks on configured collections and globals to call your revalidatePath and revalidateTag callbacks. It can probe a URL and trigger a full rebuild when the page returns 404. Requires Payload 3.37 or later and works with Next.js or any custom revalidation callbacks.

Features

  • Path and cache tag revalidation resolved per collection or global
  • Unpublish detection with a custom matcher and dedicated resolvers
  • Opt-in revalidation on document delete
  • Probe URL check that triggers a rebuild webhook on 404
  • findReferencingPaths helper to bust pages that embed a changed document
  • Debug tracing, custom logger and per-target disable switches

Use cases

  • Refresh statically generated Next.js pages when editors publish or update content
  • Rebuild the site when a new slug creates a route that is not yet deployed
  • Invalidate pages that embed a changed post inside block layouts

From the author

Payload CMS plugin for ISR-style path revalidation with optional full rebuild fallback

Installation

npm i @ggaidelevicius/payload-isr

3

Stars

0

Forks

0

Open Issues

2 months ago

Last Updated

45

Weekly Downloads

v1.2.1

npm Version

198.1 KB

Unpacked Size

0

Dependencies

GitHub stars

30 since Sep 7

Show data
GitHub stars by day (UTC)
DateStars
Dec 6, 20263
Dec 5, 20263
Dec 4, 20263
Dec 3, 20263
Dec 2, 20263
Dec 1, 20263
Nov 30, 20263
Nov 29, 20263
Nov 28, 20263
Nov 27, 20263
Nov 26, 20263
Nov 25, 20263
Nov 24, 20263
Nov 23, 20263
Nov 22, 20263
Nov 21, 20263
Nov 20, 20263
Nov 19, 20263
Nov 18, 20263
Nov 17, 20263
Nov 16, 20263
Nov 15, 20263
Nov 14, 20263
Nov 13, 20263
Nov 12, 20263
Nov 11, 20263
Nov 10, 20263
Nov 9, 20263
Nov 8, 20263
Nov 7, 20263
Nov 6, 20263
Nov 5, 20263
Nov 4, 20263
Nov 3, 20263
Nov 2, 20263
Nov 1, 20263
Oct 31, 20263
Oct 30, 20263
Oct 29, 20263
Oct 28, 20263
Oct 27, 20263
Oct 26, 20263
Oct 25, 20263
Oct 24, 20263
Oct 23, 20263
Oct 22, 20263
Oct 21, 20263
Oct 20, 20263
Oct 19, 20263
Oct 18, 20263
Oct 17, 20263
Oct 16, 20263
Oct 15, 20263
Oct 14, 20263
Oct 13, 20263
Oct 12, 20263
Oct 11, 20263
Oct 10, 20263
Oct 9, 20263
Oct 8, 20263
Oct 7, 20263
Oct 6, 20263
Oct 5, 20263
Oct 4, 20263
Oct 3, 20263
Oct 2, 20263
Oct 1, 20263
Sep 30, 20263
Sep 29, 20263
Sep 28, 20263
Sep 27, 20263
Sep 26, 20263
Sep 25, 20263
Sep 24, 20263
Sep 23, 20263
Sep 22, 20263
Sep 21, 20263
Sep 20, 20263
Sep 19, 20263
Sep 18, 20263
Sep 17, 20263
Sep 16, 20263
Sep 15, 20263
Sep 14, 20263
Sep 13, 20263
Sep 12, 20263
Sep 11, 20263
Sep 10, 20263
Sep 9, 20263
Sep 8, 20263
Sep 7, 20263
npm weekly downloads

46+34 since Sep 7

Show data
npm weekly downloads by day (UTC)
DateWeekly downloads
Dec 6, 202646
Dec 5, 202625
Dec 4, 202625
Dec 3, 202624
Dec 2, 202634
Dec 1, 202623
Nov 30, 202623
Nov 29, 202621
Nov 28, 202621
Nov 27, 202623
Nov 26, 202622
Nov 25, 202613
Nov 24, 202612
Nov 23, 202610
Nov 22, 202612
Nov 21, 20269
Nov 20, 20268
Nov 19, 20269
Nov 18, 202628
Nov 17, 202628
Nov 16, 202630
Nov 15, 202628
Nov 14, 202629
Nov 13, 202628
Nov 12, 202629
Nov 11, 20267
Nov 10, 202619
Nov 9, 202618
Nov 8, 202618
Nov 7, 202629
Nov 6, 202628
Nov 5, 202626
Nov 4, 202626
Nov 3, 202617
Nov 2, 202619
Nov 1, 202620
Oct 31, 202611
Oct 30, 202611
Oct 29, 202611
Oct 28, 202611
Oct 27, 202613
Oct 26, 202610
Oct 25, 202611
Oct 24, 202610
Oct 23, 202610
Oct 22, 202615
Oct 21, 202627
Oct 20, 202621
Oct 19, 202625
Oct 18, 202624
Oct 17, 202629
Oct 16, 202634
Oct 15, 202633
Oct 14, 2026215
Oct 13, 2026215
Oct 12, 2026211
Oct 11, 2026211
Oct 10, 2026205
Oct 9, 2026201
Oct 8, 2026198
Oct 7, 20265
Oct 6, 20265
Oct 5, 20268
Oct 4, 20267
Oct 3, 20267
Oct 2, 20266
Oct 1, 20267
Sep 30, 20266
Sep 29, 20266
Sep 28, 20265
Sep 27, 20266
Sep 26, 20269
Sep 25, 20269
Sep 24, 20267
Sep 23, 202610
Sep 22, 202611
Sep 21, 202622
Sep 20, 202621
Sep 19, 202617
Sep 18, 202618
Sep 17, 202618
Sep 16, 202616
Sep 15, 202616
Sep 14, 20263
Sep 13, 20264
Sep 12, 202610
Sep 11, 20269
Sep 10, 20269
Sep 9, 202611
Sep 8, 202611
Sep 7, 202612

Each point is npm's rolling 7-day download count.

Health Score

65/100Good

Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.

Badge for your README

Payload Directory health badge
Markdown
[![Payload Directory](https://payloaddirectory.dev/badge/1171481351-root.svg)](https://payloaddirectory.dev/plugins/1171481351-root)
HTML
<a href="https://payloaddirectory.dev/plugins/1171481351-root"><img src="https://payloaddirectory.dev/badge/1171481351-root.svg" alt="Payload Directory"></a>
Updated Oct 5, 2026Created Mar 3, 2026Published Oct 5, 2026

README

@ggaidelevicius/payload-isr

Payload CMS plugin that revalidates your Next.js cache when documents are published, updated, unpublished, or deleted — by path, by cache tag, or by triggering a full rebuild when route-level invalidation isn't enough.

Requirements

  • Payload ^3.37.0
  • Node ^18.20.2 || >=20.9.0
  • Next.js is the typical target but the plugin works with any revalidation callbacks

Install

pnpm add @ggaidelevicius/payload-isr
# or
npm install @ggaidelevicius/payload-isr

How it works

The plugin registers Payload afterOperation and afterChange hooks on whichever collections and globals you configure. When a hook fires:

  1. Unpublish check (collections) — for update / updateByID, unpublish.matcher is evaluated first. If it matches, unpublish-specific resolvers fire (falling back to the main resolvers if unpublish-specific ones are not provided), and shouldHandle is not consulted for that operation.
  2. Publish/update check — for non-unpublish operations, shouldHandle decides whether the document should trigger revalidation (default: document has no _status field, or _status === 'published')
  3. Probe — if probeURL is configured and fullRebuild is enabled, the plugin fetches that URL; a 404 triggers the full rebuild path and skips path/tag revalidation
  4. Revalidate — resolved paths are passed to your revalidatePath callback; resolved tags are passed to your revalidateTag callback

Delete revalidation is opt-in via onDelete on each collection target. The plugin warns at startup when a collection has update resolvers but no onDelete strategy.

Bulk collection updates invoke guards and resolvers once per successfully updated document. Each callback receives that document as result; the original bulk response, including errors, is returned unchanged to Payload.

Minimal setup

The smallest valid configuration — no tags, no full rebuild, one collection:

import { buildConfig } from 'payload'
import { payloadIsr } from '@ggaidelevicius/payload-isr'
import { revalidatePath } from 'next/cache'

export default buildConfig({
  plugins: [
    payloadIsr({
      revalidatePath: (path) => revalidatePath(path),
      collections: [
        {
          slug: 'posts',
          pathResolver: ({ result }) => [`/posts/${result.slug}`, '/posts'],
        },
      ],
    }),
  ],
})

Full example

import { buildConfig } from 'payload'
import { createPayloadIsrLogger, payloadIsr } from '@ggaidelevicius/payload-isr'
import {
  revalidatePath as nextRevalidatePath,
  revalidateTag as nextRevalidateTag,
} from 'next/cache'

export default buildConfig({
  plugins: [
    payloadIsr({
      // Emit structured debug traces for every hook/guard/branch decision.
      debug: true,
      // Prefix relative paths in debug output with this origin so URLs are clickable.
      debugURLOrigin: process.env.PUBLIC_APP_URL,
      // Logger that filters noisy config-level traces by default.
      logger: createPayloadIsrLogger(),

      // Called once per resolved path.
      // meta.mode is 'site' when a global uses revalidateAllOnChange — use
      // Next.js 'layout' scope in that case to revalidate the full layout tree.
      revalidatePath: (path, meta) => {
        if (meta.mode === 'site') {
          return nextRevalidatePath(path, 'layout')
        }
        return nextRevalidatePath(path)
      },

      // Optional. Called once per resolved tag. Omit if you don't use cache tags.
      revalidateTag: (tag) => nextRevalidateTag(tag, { expire: 0 }),

      collections: [
        {
          slug: 'posts',

          // Paths to revalidate when a post is published or updated.
          pathResolver: ({ result }) => [`/posts/${result.slug}`, '/posts'],

          // URL to probe before deciding whether a full rebuild is needed.
          // If this returns 404, fullRebuild.trigger() is called instead of revalidating paths/tags.
          probeURL: ({ result }) => `${process.env.PUBLIC_APP_URL}/posts/${result.slug}`,

          // Cache tags to invalidate.
          tagResolver: ({ result }) => ['posts', `post:${result.id}`],

          // onDelete is optional, but without it this target won't revalidate on deletes.
          // The plugin emits a startup warning for this misconfiguration.
          onDelete: {
            pathResolver: ({ id }) => [`/posts/${id}`, '/posts'],
            tagResolver: ({ id }) => ['posts', `post:${id}`],
          },
        },
      ],

      globals: [
        {
          slug: 'site-settings',
          // Revalidate the entire site (calls revalidatePath('/', 'layout') via meta.mode === 'site').
          // Cannot be combined with pathResolver on the same target.
          revalidateAllOnChange: true,
          tagResolver: () => ['site-settings', 'global'],
        },
      ],

      fullRebuild: {
        // Disable in development to avoid accidentally triggering deploys.
        enabled: process.env.NODE_ENV === 'production',
        // Fires when a probeURL returns 404 (the default shouldTrigger condition).
        trigger: async () => {
          await fetch(process.env.REBUILD_WEBHOOK_URL!, { method: 'POST' })
        },
      },
    }),
  ],
})

Plugin options

Top-level (payloadIsr({ ... }))

OptionTypeRequiredDescription
revalidatePath(path, meta) => void | Promise<void>No*Called for each resolved path. See Revalidation metadata.
revalidateTag(tag, meta?) => void | Promise<void>No*Called for each resolved tag. Omit only if you do not use tag-based caching.
collectionsCollectionISRTarget[]NoCollection revalidation targets.
globalsGlobalISRTarget[]NoGlobal revalidation targets.
fullRebuildFullRebuildConfigNoFull rebuild fallback. See Full rebuild fallback.
logger{ error, warn, info? }NoCustom logger. Defaults to console. Use createPayloadIsrLogger() for structured output with built-in filtering.
debugbooleanNoEmit structured trace events via logger.info for every hook, guard, and branch decision.
debugURLOriginstringNoBase URL prepended to relative paths in debug output, making logged paths absolute and clickable.
disabledbooleanNoDisable the plugin entirely without removing it from config.

* At least one of revalidatePath or revalidateTag is required.

TypeScript note: callback args in collections and globals are inferred from each target's slug using Payload's generated types. Invalid field access is caught at compile time. Each target requires at least one revalidation strategy at the type level — the compiler will error if a target has no resolver.

Collection target

OptionTypeDefaultDescription
slugstring—Collection slug. Must match your Payload collection.
disabledbooleanfalseSkip this target without removing it from config.
pathResolver(args) => string[]—Returns paths to revalidate when a document is published or updated.
tagResolver(args) => string[]—Returns cache tags to invalidate.
referencePathResolver(args) => string[]—Additional paths to revalidate, merged with pathResolver results. Use findReferencingPaths() here to also bust other pages that embed this document.
referenceTagResolver(args) => string[]—Additional tags to invalidate, merged with tagResolver results.
probeURL(args) => string—URL to fetch before triggering full rebuild. Required for full rebuild to ever fire on this target.
operationsstring[]['create', 'update', 'updateByID']Which Payload operations trigger this target.
shouldHandle(args) => booleanChecks _status === 'published' (or no _status field)Custom gate. Return false to skip revalidation for this operation.
unpublishUnpublishConfig—Override unpublish detection and/or unpublish-specific path/tag resolvers.
onDeleteOnDeleteConfig—Opt-in delete revalidation. Without this, deletes are skipped for this target and a startup warning is emitted.

At least one of pathResolver, tagResolver, referencePathResolver, referenceTagResolver, or probeURL is required at the type level.

Global target

OptionTypeDefaultDescription
slugstring—Global slug. Must match your Payload global.
disabledbooleanfalseSkip this target without removing it from config.
revalidateAllOnChangeboolean—Revalidate the entire site on every change. Passes meta.mode === 'site' to revalidatePath. Cannot be combined with pathResolver.
revalidateAllPathstring'/'Path passed to revalidatePath when revalidateAllOnChange is enabled. Must be absolute.
pathResolver(args) => string[]—Returns targeted paths. Use this when revalidateAllOnChange is too broad.
tagResolver(args) => string[]—Returns cache tags to invalidate.
shouldHandle(args) => booleanChecks _status === 'published' (or no _status field)Custom gate.
probeURL(args) => string—URL to probe before full rebuild decision.

At least one strategy required: revalidateAllOnChange: true, or at least one of pathResolver, tagResolver, probeURL.

Full rebuild config

OptionTypeDefaultDescription
enabledbooleantrue when configuredWhether full rebuild is active. Recommended: process.env.NODE_ENV === 'production'.
probeTimeoutMsnumber10000Maximum probe duration in milliseconds. Must be finite, positive, and at most 2147483647; invalid values warn and use the default.
trigger(context) => void | Promise<void>—Required. What to call when a rebuild is triggered.
shouldTrigger(context) => booleancontext.probeStatus === 404Override the condition for triggering.

trigger receives a FullRebuildContext with: probeStatus, probeURL, reason, scope, slug.

Revalidation metadata

When configured, both revalidatePath and revalidateTag receive a meta argument describing why revalidation is happening.

revalidatePath(path, meta)

meta: {
  mode: 'path' | 'site'  // 'site' only for globals with revalidateAllOnChange
  reason: RevalidationReason
  scope: 'collection' | 'global'
  slug: string
}

The mode field is the primary reason to branch on meta — Next.js requires a 'layout' scope argument when you want to invalidate the full layout tree:

revalidatePath: (path, meta) => {
  if (meta.mode === 'site') {
    return nextRevalidatePath(path, 'layout')
  }
  return nextRevalidatePath(path)
},

revalidateTag(tag, meta?)

The Next.js 16 example uses { expire: 0 } for immediate expiration after CMS changes. Use 'max' if you prefer serving stale content while refreshing it in the background. See the Next.js tag revalidation documentation.

meta?: {
  reason: RevalidationReason
  scope: 'collection' | 'global'
  slug: string
}

Revalidation reasons

ReasonWhen
'collection-update'Collection create or update operation
'collection-unpublish'Update that transitions a document from published to draft
'collection-delete'Collection delete operation
'global-update'Global doc change

Default behaviors

These are the defaults to be aware of — getting them wrong is a common source of missed revalidation:

shouldHandle — defaults to doc._status === 'published' or, if the document has no _status field at all, true. If you don't use Payload drafts, every publish/update will pass the default guard automatically. If you do use drafts, only published docs trigger revalidation by default. Override with a custom shouldHandle to change this. Note: collection unpublish handling runs before this guard.

operations — defaults to ['create', 'update', 'updateByID']. Override to select a subset of these content operations. Unpublish matching runs before this filter.

onDelete — not configured by default. Deletes are skipped without it. The plugin warns at startup for collection targets that define update resolvers but no onDelete.

revalidateAllPath — defaults to '/' when revalidateAllOnChange: true.

fullRebuild.shouldTrigger — defaults to context.probeStatus === 404. Override to trigger on other status codes or custom logic.

fullRebuild without probeURL — if fullRebuild is enabled but no target has a probeURL, no probe ever runs and the rebuild trigger is never reached. The plugin emits a warning at startup.

Invalid probeURL values — if a resolver returns an empty, relative, or non-HTTP URL, the plugin warns and skips probing for that operation.

Probe failures — network failures and timeouts produce probeStatus: null, so normal path/tag revalidation continues unless a custom shouldTrigger handles that status. Probe resolvers are not called when fullRebuild is absent or explicitly disabled.

Callback failures — plugin guard, resolver, revalidation, and rebuild-trigger errors propagate to Payload. Subsequent callbacks for the operation are not guaranteed to run. Handle recoverable errors inside your callbacks when continued processing is required.

Unpublish detection

When a collection update is detected as an unpublish, the plugin uses unpublish-specific resolvers if provided, falling back to the main resolvers.

Default unpublish matcher: the operation must be update or updateByID, and request data must include _status: 'draft'. Extra fields are allowed. This is an update-to-draft signal and does not strictly validate previous persisted state.

If your app uses a different field to control publish state (e.g. isPublished: boolean), provide a custom unpublish.matcher:

{
  slug: 'posts',
  pathResolver: ({ result }) => [`/posts/${result.slug}`, '/posts'],
  unpublish: {
    // Detect your custom unpublish pattern
    matcher: ({ args, operation }) => {
      if (operation !== 'update' && operation !== 'updateByID') return false
      return args.data.isPublished === false
    },
    // Optional: different paths/tags on unpublish (falls back to main resolvers if omitted)
    pathResolver: ({ result }) => [`/posts/${result.slug}`, '/posts'],
    tagResolver: ({ result }) => ['posts', `post:${result.id}`],
  },
}

Delete revalidation

Deletes do not trigger revalidation unless onDelete is configured on the target. The plugin warns at startup when onDelete is missing. The delete hook receives the deleted document and its ID:

{
  slug: 'posts',
  pathResolver: ({ result }) => [`/posts/${result.slug}`, '/posts'],
  onDelete: {
    pathResolver: ({ doc, id }) => [
      // doc is the deleted document — use its fields if available
      typeof doc.slug === 'string' ? `/posts/${doc.slug}` : `/posts/${id}`,
      '/posts',
    ],
    tagResolver: ({ id }) => ['posts', `post:${id}`],
  },
}

Finding referencing pages

When a document changes, other pages that embed or reference that document may also need their cache busted — for example, a pages entry that includes a post inside its block layout.

findReferencingPaths() handles this automatically. You give it the changed document's ID and the collections/globals to search, and it returns the paths of any documents that contain a reference to it. Use it inside referencePathResolver:

import { findReferencingPaths, payloadIsr } from '@ggaidelevicius/payload-isr'

{
  slug: 'posts',
  pathResolver: ({ result }) => [`/posts/${result.slug}`, '/posts'],
  referencePathResolver: ({ req, result }) =>
    findReferencingPaths({
      payload: req.payload,
      req,
      referencedValues: result.id,
      targets: {
        collections: ['pages', 'news'],
        globals: ['homepage'],
      },
      fieldPaths: ['layout'],
    }),
}

This fetches candidate documents from pages, news, and homepage, then applies the default published filter before matching references and returning paths.

How matching works

The helper walks the values at each fieldPath (or the roots returned by getSearchRoots) and checks whether any string or number matches one of the referencedValues. Dotted paths traverse arrays of blocks or relationships: layout.relatedPost checks relatedPost in every layout entry. Explicit indexes such as layout.0.relatedPost select only that entry. Matching supports deeply nested and cyclic search roots.

By default, only published documents are candidates (_status === 'published', or docs without _status). Override this with shouldInclude.

By default, queries run with depth: 0 and overrideAccess: true. This keeps relationship values as IDs (better for stable matching) and avoids access-scoped misses in system-level revalidation. Override with queryDepth / overrideAccess if your project needs different behavior.

Pass the hook's req to preserve its transaction, locale, user, and context. This is especially useful with overrideAccess: false. A candidate's failing shouldInclude, getSearchRoots, or resolvePaths callback is logged and skips only that document; other candidates continue to be checked.

How paths are resolved

For each matching document, the path is determined by the first of these that applies:

  1. The last URL in its breadcrumbs array (if present and starts with /)
  2. /${doc.slug} (if the document has a non-empty slug field)
  3. /${doc.id}
  4. / — only for globals that have none of the above

Override with resolvePaths when your routing doesn't follow this convention. Paths returned by resolvePaths must be absolute (start with /).

Telling the helper where to look

The helper doesn't know which fields store your block or relation data — you need to point it there.

fieldPaths accepts dot-separated paths to the fields that contain block or relation data:

fieldPaths: ['layout', 'hero.blocks', 'sidebar.content']

getSearchRoots is an escape hatch for when references don't live in predictable fields — it receives the full document and returns the values to search:

getSearchRoots: (doc, meta) => {
  // Search the entire document for pages, only the hero section for others
  if (meta.slug === 'pages') return [doc]
  return [doc.hero]
}

When both fieldPaths and getSearchRoots are provided, their results are combined. At least one is required.

Custom path resolution

Override resolvePaths when the default path convention doesn't match your routing:

referencePathResolver: ({ req, result }) =>
  findReferencingPaths({
    payload: req.payload,
    req,
    referencedValues: result.id,
    targets: {
      collections: ['pages', 'news'],
    },
    fieldPaths: ['hero.blocks', 'layout'],
    resolvePaths: (doc, meta) => {
      if (meta.slug === 'news' && typeof doc.slug === 'string') {
        return [`/news/${doc.slug}`]
      }
      return typeof doc.slug === 'string' ? [`/${doc.slug}`] : []
    },
  })

Options reference

OptionRequiredDescription
payloadYesPayload instance. Available as args.req.payload in hook resolvers.
reqNoOriginating Payload request, preserving its transaction, locale, user, and context. Pass the hook's req.
referencedValuesYesThe ID(s) to search for — typically result.id. Accepts a single value or an array; null/undefined entries are ignored.
targetsYes{ collections?, globals? } — which slugs to scan for references.
fieldPathsOne of fieldPaths/getSearchRootsDot-separated field paths to inspect on each candidate document (e.g. ['layout', 'hero.blocks']). Fields that don't exist on a document are silently skipped.
getSearchRootsOne of fieldPaths/getSearchRootsFunction returning the values to search for a given document. Combined with fieldPaths results when both are provided.
resolvePathsNoCustom route mapper for matching documents. Must return absolute paths (starting with /). Defaults to: breadcrumb URL → /${slug} → /${id} → / (globals only).
shouldIncludeNoCustom filter applied to each candidate document before the reference search runs. Defaults to published docs or docs without _status.
queryDepthNoDepth passed to Payload queries. Defaults to 0. Increase if you intentionally want populated relationship objects in the search roots.
overrideAccessNoWhether to bypass access control when scanning candidates. Defaults to true to avoid missed revalidation due to user-scoped access.
loggerNoLogger for warnings from the helper (failed queries, non-absolute paths). Defaults to console. Pass the same logger you configured on the plugin to keep output consistent.

Database adapter notes

MongoDB — MongoDB stores relationship IDs embedded within each document's structure. There is no join table or foreign-key index to reverse-query, so finding "all pages that reference post X" requires a full collection scan regardless. findReferencingPaths is the practical solution here.

PostgreSQL / SQLite — Payload's SQL adapters store relationships in dedicated join tables (e.g. pages_rels). In principle you could query those tables directly to find referencing documents without fetching full documents. findReferencingPaths doesn't do this — it uses payload.find() and scans the returned documents in memory, which is database-agnostic but less targeted than a raw SQL query. For large collections on a SQL adapter, a direct Drizzle query against the _rels table would be more efficient, though it requires knowing Payload's internal table naming conventions (which vary by collection and field structure).

Performance note

findReferencingPaths fetches every document in each target collection on every publish event. Keep targets narrow — only include collections that actually store references to the changed document type.

Full rebuild fallback

fullRebuild is a fallback for situations where path/tag invalidation misses newly valid routes — for example, when a slug changes and the new URL has never been cached, or when catch-all routes return 404 until a new build is deployed.

When to enable it:

  • Slug or route shape changes that create a URL not yet present in the current deployment
  • Catch-all or nested routing where newly published content returns 404 until a rebuild
  • CDN or edge cache scenarios where route/tag revalidation alone is insufficient

How it works:

  1. fullRebuild must be configured, with enabled not set to false
  2. The target must have a probeURL resolver — without it, no probe runs
  3. Plugin fetches probeURL after a publish/update
  4. If fullRebuild.shouldTrigger(context) returns true (default: probeStatus === 404), trigger() is called
  5. Path/tag revalidation is skipped when a rebuild triggers
fullRebuild: {
  enabled: process.env.NODE_ENV === 'production',
  trigger: async (context) => {
    // context: { probeStatus, probeURL, reason, scope, slug }
    await fetch(process.env.REBUILD_WEBHOOK_URL!, { method: 'POST' })
  },
}

Common trigger implementations:

  • Generic HTTP deploy webhook
  • CI/CD provider API (GitHub Actions, GitLab CI, CircleCI)
  • Hosted platform rebuild endpoint (Vercel, Netlify, Cloudflare)
  • Internal queue or job dispatcher

Route contract alignment

All ISR inputs for a content type should map to the same routing contract your app actually serves. Misalignment means revalidating paths that aren't cached, or probing URLs that don't match what's live.

Rules of thumb:

  • pathResolver should return the paths your app actually caches and serves
  • probeURL should be the user-facing URL you expect to exist after a successful deploy
  • If your app serves both /posts/[id] and /posts/[slug], revalidate both
  • If a slug can change, referencePathResolver can revalidate the previous URL if your resolver can derive it (e.g. from stored history)

Example — helper functions that stay consistent across resolvers:

const getPostPaths = (doc: { id: string | number; slug?: null | string }) => {
  const idPath = `/posts/${String(doc.id)}`
  const slugPath = typeof doc.slug === 'string' && doc.slug.trim() ? `/posts/${doc.slug.trim()}` : null
  return [slugPath, idPath, '/posts'].filter(Boolean) as string[]
}

const getPostProbeURL = (doc: { id: string | number; slug?: null | string }) =>
  new URL(
    typeof doc.slug === 'string' && doc.slug.trim()
      ? `/posts/${doc.slug.trim()}`
      : `/posts/${String(doc.id)}`,
    process.env.PUBLIC_APP_URL,
  ).toString()

// Use in config:
{
  slug: 'posts',
  pathResolver: ({ result }) => getPostPaths(result),
  probeURL: ({ result }) => getPostProbeURL(result),
  onDelete: {
    pathResolver: ({ doc, id }) => getPostPaths({ id, slug: doc.slug }),
  },
}

Debug and logging

Enable debug traces:

payloadIsr({
  debug: true,
  logger: createPayloadIsrLogger(),
  // ...
})

createPayloadIsrLogger() prefixes output with [payload-isr] and filters out noisy config.* setup traces by default. To include config-level events:

logger: createPayloadIsrLogger({ includeConfigDebugEvents: true })

Bring your own logger by passing any object with error, warn, and optionally info methods:

logger: {
  error: (...args) => myLogger.error(...args),
  warn: (...args) => myLogger.warn(...args),
  info: (...args) => myLogger.info(...args),
}

Startup preflight warnings — the plugin validates configuration at init and warns about:

  • Duplicate target slugs (hooks may fire multiple times)
  • Targets with no revalidation strategy
  • Collection targets missing delete strategy (onDelete)
  • Collection targets with onDelete configured but no resolvers inside it
  • Path resolvers configured without a revalidatePath callback
  • tagResolver without a revalidateTag callback
  • fullRebuild enabled with no probeURL resolvers
  • revalidateAllOnChange and pathResolver on the same global target
  • Non-absolute revalidateAllPath

Local development

pnpm hooks:install   # install commit-msg and other git hooks
pnpm dev             # start the bundled dev app
pnpm test:int        # run all unit and integration tests once
pnpm lint            # check source, tests, and development configuration
pnpm build           # build the plugin
pnpm publish:check   # lint, test, rebuild, and inspect the package contents

Builds use the TypeScript 7 native compiler. The typescript dependency aliases Microsoft's TypeScript 6 compatibility package for tools that need the JavaScript compiler API. The parser overrides keep Payload's lint configuration compatible with ESLint 10. Integration tests create a temporary MongoDB replica set and close it, along with Payload, when the suite finishes.

Pull requests and pushes to main run pnpm publish:check in CI. Publishing remains restricted to commits with a valid release marker.

Environment variables for the bundled dev/ app:

VariableDefaultDescription
PAYLOAD_ISR_DEBUG1Emit branch-level debug traces
PAYLOAD_ISR_DEBUG_CONFIGoffInclude noisy config.* trace events
PAYLOAD_ISR_FULL_REBUILDoffEnable full-rebuild fallback simulation
PAYLOAD_ISR_PROBE_ORIGINhttp://127.0.0.1:3000Base URL for probe requests

Dev API endpoints:

  • GET /api/isr-debug — inspect recorded revalidation telemetry
  • DELETE /api/isr-debug — clear recorded telemetry

Release commit marker guard: commit messages containing (release...) must use exactly one of (release:patch), (release:minor), or (release:major). Invalid values (e.g. (release:path)) are rejected by the commit-msg hook.

Similar plugins