Skip to content

@plenary/next

@plenary/next connects Plenary to the Next.js cache. It gives you a route handler that receives Plenary webhooks and calls revalidatePath or revalidateTag, and a fetch wrapper that tags every content read so one webhook can refresh every page that used an entry. It depends on @plenary/client and has next 14, 15, or 16 as a peer dependency. It does not depend on React.

Terminal window
npm install @plenary/client @plenary/next

This page documents version 1.0.x. For a step-by-step build, see Instant revalidation.

Export Import from Kind
createRevalidateHandler @plenary/next App Router route handler factory
createPagesRevalidateHandler @plenary/next/pages Pages Router API route factory
createTaggedFetch @plenary/next fetch wrapper that adds cache tags
modelTag, modelEntriesTag, entryTag @plenary/next Tag name builders
planRevalidation @plenary/next The pure decision function, for custom handlers
entryUrl @plenary/next Default URL builder
RevalidateOptions, RevalidatePaths, RevalidationPlan @plenary/next Types
function createRevalidateHandler(options: RevalidateOptions): (request: Request) => Promise<Response>;

Returns an App Router POST handler. For each request it verifies the secret, parses the payload, works out which paths (and optionally tags) the event affects, and revalidates them.

app/api/revalidate/route.ts
import { createRevalidateHandler } from "@plenary/next";
const secret = process.env.PLENARY_WEBHOOK_SECRET;
const handler = createRevalidateHandler({
secret: secret ?? "",
paths: {
post: ({ entry }) => (entry.slug ? ["/blog", `/blog/${entry.slug}`] : ["/blog"]),
},
});
export async function POST(request: Request) {
// Refuse everything when the secret is not configured.
if (!secret) {
return Response.json({ message: "PLENARY_WEBHOOK_SECRET is not set" }, { status: 503 });
}
return handler(request);
}

Then add a webhook in the console that points at https://your-site.example.com/api/revalidate, subscribes to the entry events, and sends a header x-plenary-secret marked Secret with the same value as PLENARY_WEBHOOK_SECRET. The revalidation example walks through it.

Option Type Default Description
secret string Required The shared secret configured on the webhook.
secretHeader string "x-plenary-secret" Header the secret arrives in.
secretQuery string "secret" Query parameter checked when the header is absent.
paths Record<string, RevalidatePaths> None Paths to revalidate per model key. A model listed here replaces the default URL entirely.
entryUrl (payload: EntryWebhookPayload) => string | null | undefined entryUrl Builds the path for models not listed in paths. Return null to revalidate no path.
events EntryWebhookEvent[] All five entry events Events that trigger revalidation. Others are answered but ignored.
tags boolean false Also revalidate the model and entry cache tags. App Router only.
type RevalidatePaths =
| string
| string[]
| ((payload: EntryWebhookPayload) => string | string[] | null | undefined);

A path function receives the full entry webhook payload, so you can use entry.slug, entry.path, entry.locale, model.key, and changed. Duplicate paths are removed. Paths are passed to revalidatePath as they are, so they must be route paths on your site, such as /blog/hello-plenary.

To keep the default URL and add more, call entryUrl yourself:

import { createRevalidateHandler, entryUrl } from "@plenary/next";
export const POST = createRevalidateHandler({
secret: process.env.PLENARY_WEBHOOK_SECRET ?? "",
paths: {
page: (payload) => [entryUrl(payload) ?? "/", "/sitemap.xml"],
},
});
Request Status Response body Cache effect
Not POST 405 { "message": "Method not allowed" } None
No secret configured (empty or unset) 500 { "message": "Webhook secret is not configured" } None
Secret missing or wrong 401 { "message": "Invalid webhook secret" } None
Body not JSON, or not a Plenary payload 400 { "message": "…" } None
form.submitted, or an event not in events 200 { "revalidated": false, "ignored": "<event>" } None
Event webhook.test 200 { "test": true, "paths": […], "tags": […] } None (dry run)
An entry event 200 { "revalidated": true, "paths": […], "tags": […] } revalidatePath for each path, revalidateTag for each tag

The 4xx answers make Plenary fail the delivery at once rather than retry it. Plenary retries 5xx responses and timeouts with backoff for about seven hours, and gives each attempt 10 seconds. Revalidation is idempotent, so a retried or duplicated delivery is harmless.

On Next.js 16, revalidateTag takes a second “profile” argument, and calling it with one argument is deprecated. createRevalidateHandler with tags: true calls it with one argument, which logs a deprecation warning and expires the tagged data immediately: the next visitor waits for a fresh render, and if your Plenary instance is unreachable at that moment, the page errors instead of serving the cached copy.

On Next.js 16, when you use tags, write the handler yourself with planRevalidation and the "max" profile, which serves the cached page while a fresh one renders in the background:

app/api/revalidate/route.ts
import { revalidateTag } from "next/cache";
import { parseWebhookRequest, PlenaryWebhookError } from "@plenary/client";
import { planRevalidation, type RevalidateOptions } from "@plenary/next";
export async function POST(request: Request) {
const secret = process.env.PLENARY_WEBHOOK_SECRET;
if (!secret) {
return Response.json({ message: "PLENARY_WEBHOOK_SECRET is not set" }, { status: 503 });
}
// Tags reach every page that read the content, so no paths are needed.
const options: RevalidateOptions = { secret, tags: true, entryUrl: () => null };
let payload;
try {
payload = await parseWebhookRequest(request, options);
} catch (err) {
if (err instanceof PlenaryWebhookError) {
return Response.json({ message: err.message }, { status: err.status });
}
throw err;
}
const plan = planRevalidation(payload, options);
if (!plan.relevant) return Response.json({ revalidated: false, ignored: payload.event });
if (plan.test) return Response.json({ test: true, tags: plan.tags });
for (const tag of plan.tags) revalidateTag(tag, "max");
return Response.json({ revalidated: true, tags: plan.tags });
}

Path revalidation (revalidatePath) is not affected; the handler works unchanged on Next.js 16 when you use paths without tags.

import { createPagesRevalidateHandler } from "@plenary/next/pages";
function createPagesRevalidateHandler(
options: RevalidateOptions,
): (req: NextApiRequest, res: NextApiResponse) => Promise<void>;

The Pages Router version. It takes the same options and gives the same responses, and calls res.revalidate(path) for each path. The tags option is ignored, because cache tags are an App Router feature.

pages/api/revalidate.ts
import { createPagesRevalidateHandler } from "@plenary/next/pages";
export default createPagesRevalidateHandler({
secret: process.env.PLENARY_WEBHOOK_SECRET ?? "",
paths: {
post: ({ entry }) => (entry.slug ? ["/blog", `/blog/${entry.slug}`] : ["/blog"]),
},
});

The handler reads req.body, so leave Next.js’s default JSON body parser on for this route. res.revalidate applies to pages built with getStaticProps. If revalidating any path fails, the handler rejects, Next.js answers 500, and Plenary retries the delivery.

function createTaggedFetch(baseFetch?: typeof fetch): typeof fetch;

Wraps a fetch so that every GET to the Content API carries Next.js cache tags. Pass the result to createClient:

lib/plenary.ts
import { createClient } from "@plenary/client";
import { createTaggedFetch } from "@plenary/next";
// Next.js 15 and later do not cache fetch by default. Opt in, so reads stay
// cached until a webhook revalidates their tags.
const cachedFetch: typeof fetch = (input, init) => fetch(input, { ...init, cache: "force-cache" });
export const plenary = createClient({
baseUrl: process.env.PLENARY_BASE_URL!,
apiKey: process.env.PLENARY_API_KEY!,
siteKey: process.env.PLENARY_SITE_KEY ?? "default",
locale: process.env.PLENARY_LOCALE ?? "en-us",
fetch: createTaggedFetch(cachedFetch),
});
Request Tags added
GET /api/v1/content/{model} plenary:model:{model}
GET /api/v1/content/{model}/{slugOrId} plenary:model-entries:{model}, plenary:entry:{slugOrId}
GET /api/v1/content/{model} with where: { slug } naming one slug plenary:model-entries:{model}, plenary:entry:{slug}
Anything else (forms, media, GraphQL, non-GET) None; passed through untouched

A GraphQL read is a POST whose URL names no model, so tag it yourself: plenary.graphql takes tags, which it sends as next.tags on the request, and the tag helpers spell them.

const data = await plenary.graphql(query, vars, { tags: [modelTag("post")] });

A read of one entry carries no model tag, so editing one entry does not refresh the pages of the model’s other entries. Tags are merged with any next.tags already on the request. baseFetch defaults to the global fetch.

Tags only matter for responses Next.js caches. On Next.js 15 and 16, fetch is uncached unless you ask for it, so pass a base fetch that sets cache: "force-cache" (as above) or next: { revalidate: <seconds> }. During next dev, you may prefer to leave caching off so edits show without a webhook:

const cachedFetch: typeof fetch = (input, init) =>
fetch(input, process.env.NODE_ENV === "production" ? { ...init, cache: "force-cache" } : init);
function modelTag(modelKey: string): string; // "plenary:model:<modelKey>"
function modelEntriesTag(modelKey: string): string; // "plenary:model-entries:<modelKey>"
function entryTag(slugOrId: string): string; // "plenary:entry:<slugOrId>"
Tag Applied to Revalidated by a webhook for
plenary:model:{model_key} Lists and singletons of the model Any entry event on that model
plenary:model-entries:{model_key} Reads of one entry of the model An event whose changed names slug or path, so the page at an entry’s old URL is refreshed
plenary:entry:{slug} Reads of one entry by slug An event on the entry with that slug
plenary:entry:{id} Reads of one entry by ID An event on the entry with that ID

A webhook with tags: true revalidates the model tag, the entry’s ID tag, and (when the entry has a slug) its slug tag. So a change to one post refreshes every page that listed posts and every page that read that post. Entry tags do not include the locale: translations of an entry share a slug, so a change to one translation also refreshes pages that read the others by slug.

Use the builders to tag your own fetches or to revalidate by hand, for example from a Server Action:

app/actions.ts
"use server";
import { revalidateTag } from "next/cache";
import { modelTag } from "@plenary/next";
export async function refreshAllPosts() {
// Next.js 16 signature. On Next.js 14 and 15, call revalidateTag(modelTag("post")).
revalidateTag(modelTag("post"), "max");
}
function planRevalidation(payload: WebhookPayload, options: RevalidateOptions): RevalidationPlan;
interface RevalidationPlan {
relevant: boolean; // false for form payloads and events not in options.events
test: boolean; // true for "webhook.test": report, do not revalidate
paths: string[];
tags: string[];
}

The decision both handlers use, with no framework calls. Use it to build a custom handler: a different tag profile (as in Next.js 16 and tags), logging, a queue, or another framework.

function entryUrl(payload: EntryWebhookPayload): string | null;

The default path for an entry: its folder path joined with its slug. A root-folder entry slugged home is the home page, /.

entry.path entry.slug Result
/ hello-plenary /hello-plenary
/ home /
/blog spring-sale /blog/spring-sale
any none (singleton) null

This matches your site’s URLs only if your routes mirror the folder tree with no prefix. A blog served at /blog/{slug} from a model with no folders needs a paths entry or a custom entryUrl. Locale is not part of the default path; add it in entryUrl if your routes include it.

Variable Used for
PLENARY_WEBHOOK_SECRET The value of the secret header configured on the webhook. Generate a long random string, for example with openssl rand -hex 32.
PLENARY_BASE_URL, PLENARY_API_KEY, PLENARY_SITE_KEY, PLENARY_LOCALE The client configuration. See SDK overview.

The variable names are a convention; the package reads nothing from the environment itself.