Lets a project define who may do what in one access policy file that covers every collection, global, field and job operation. The policy is applied to the built config with a wrapper function, and the boot fails when entries are missing, unknown or still hand-written. Plugins built on it declare named capabilities that the project grants, and their endpoints and Local API calls go through the guard. Requires Node 22.22 or later and Payload 3.90 or later, and is server-only.
One guarded door for Payload CMS plugins: an access policy file, typed predicates, guarded endpoints and Local API wrappers
Installation
npm i @focus-reactive/payload-plugin-guard37
Stars
5
Forks
33
Open Issues
Today
Last Updated
664
Weekly Downloads
v0.1.1
npm Version
295.2 KB
Unpacked Size
1
Dependencies
37+22 since Sep 7
| Date | Stars |
|---|---|
| Dec 6, 2026 | 37 |
| Dec 5, 2026 | 37 |
| Dec 4, 2026 | 37 |
| Dec 3, 2026 | 37 |
| Dec 2, 2026 | 37 |
| Dec 1, 2026 | 36 |
| Nov 30, 2026 | 35 |
| Nov 29, 2026 | 35 |
| Nov 28, 2026 | 34 |
| Nov 27, 2026 | 34 |
| Nov 26, 2026 | 34 |
| Nov 25, 2026 | 34 |
| Nov 24, 2026 | 34 |
| Nov 23, 2026 | 34 |
| Nov 22, 2026 | 34 |
| Nov 21, 2026 | 34 |
| Nov 20, 2026 | 33 |
| Nov 19, 2026 | 32 |
| Nov 18, 2026 | 32 |
| Nov 17, 2026 | 32 |
| Nov 16, 2026 | 32 |
| Nov 15, 2026 | 32 |
| Nov 14, 2026 | 32 |
| Nov 13, 2026 | 32 |
| Nov 12, 2026 | 32 |
| Nov 11, 2026 | 32 |
| Nov 10, 2026 | 32 |
| Nov 9, 2026 | 31 |
| Nov 8, 2026 | 31 |
| Nov 7, 2026 | 31 |
| Nov 6, 2026 | 31 |
| Nov 5, 2026 | 31 |
| Nov 4, 2026 | 30 |
| Nov 3, 2026 | 30 |
| Nov 2, 2026 | 30 |
| Nov 1, 2026 | 30 |
| Oct 31, 2026 | 30 |
| Oct 30, 2026 | 30 |
| Oct 29, 2026 | 30 |
| Oct 28, 2026 | 30 |
| Oct 27, 2026 | 30 |
| Oct 26, 2026 | 30 |
| Oct 25, 2026 | 30 |
| Oct 24, 2026 | 29 |
| Oct 23, 2026 | 29 |
| Oct 22, 2026 | 29 |
| Oct 21, 2026 | 29 |
| Oct 20, 2026 | 29 |
| Oct 19, 2026 | 29 |
| Oct 18, 2026 | 29 |
| Oct 17, 2026 | 27 |
| Oct 16, 2026 | 26 |
| Oct 15, 2026 | 26 |
| Oct 14, 2026 | 26 |
| Oct 13, 2026 | 25 |
| Oct 12, 2026 | 25 |
| Oct 11, 2026 | 25 |
| Oct 10, 2026 | 25 |
| Oct 9, 2026 | 25 |
| Oct 8, 2026 | 25 |
| Oct 7, 2026 | 25 |
| Oct 6, 2026 | 24 |
| Oct 5, 2026 | 24 |
| Oct 4, 2026 | 24 |
| Oct 3, 2026 | 23 |
| Oct 2, 2026 | 22 |
| Oct 1, 2026 | 22 |
| Sep 30, 2026 | 20 |
| Sep 29, 2026 | 20 |
| Sep 28, 2026 | 20 |
| Sep 27, 2026 | 20 |
| Sep 26, 2026 | 19 |
| Sep 25, 2026 | 18 |
| Sep 24, 2026 | 18 |
| Sep 23, 2026 | 18 |
| Sep 22, 2026 | 18 |
| Sep 21, 2026 | 18 |
| Sep 20, 2026 | 18 |
| Sep 19, 2026 | 18 |
| Sep 18, 2026 | 18 |
| Sep 17, 2026 | 18 |
| Sep 16, 2026 | 18 |
| Sep 15, 2026 | 18 |
| Sep 14, 2026 | 18 |
| Sep 13, 2026 | 17 |
| Sep 12, 2026 | 17 |
| Sep 11, 2026 | 17 |
| Sep 10, 2026 | 16 |
| Sep 9, 2026 | 16 |
| Sep 8, 2026 | 16 |
| Sep 7, 2026 | 15 |
Shared by 15 plugins in focusreactive/payload-plugins.
Trends appear after 7 days of data. Collecting since Dec 5 — 2 daily snapshots so far.
Each point is npm's rolling 7-day download count.
Health Score
Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.
Badge for your README
[](https://payloaddirectory.dev/plugins/1177993877-payload-plugin-guard)<a href="https://payloaddirectory.dev/plugins/1177993877-payload-plugin-guard"><img src="https://payloaddirectory.dev/badge/1177993877-payload-plugin-guard.svg" alt="Payload Directory"></a>README
One guarded door for the @focus-reactive/* plugins for Payload CMS v3.
The project writes who may do what in one access policy file, and every plugin built on the guard reads its rights from that file instead of checking req.user on its own.
The package is server-only and needs Node 22.22 or later (engines.node is >=22.22.0); it was verified on Node 22, 24 and 26.
Run the server on Node, not on the bun runtime: there safeFetch throws, because bun's fetch cannot be pinned to the checked addresses, so every plugin request that goes through it fails.
Its one runtime dependency is undici, which safeFetch uses to pin its connection; payload (^3.90.0) is its only peer dependency.
where), with combinators.Write the policy next to payload.config.ts and check it against the generated types with satisfies.
A collection or global that has no entry, an entry for a slug that does not exist, or a missing operation is a type error.
// src/access.policy.ts
import {
and,
anyone,
defineAccessPolicy,
filter,
gate,
nobody,
or,
type AccessPolicy,
} from "@focus-reactive/payload-plugin-guard";
import type { PayloadRequest } from "payload";
import type { Config } from "./payload-types";
const roles = (req: PayloadRequest): string[] =>
req.user?.collection === "users" ? (req.user.roles ?? []) : [];
const isAdmin = gate(({ req }) => roles(req).includes("admin"));
const isEditor = gate(({ req }) => roles(req).some((role) => ["admin", "editor"].includes(role)));
const isStaff = gate(({ req }) => req.user?.collection === "users");
const ownPages = filter(({ req }) =>
req.user?.collection === "users" ? { owner: { equals: req.user.id } } : false
);
export const accessPolicy = defineAccessPolicy({
collections: {
users: {
create: isAdmin,
read: isStaff,
update: isAdmin,
delete: isAdmin,
unlock: isAdmin,
admin: isStaff,
fields: { roles: { update: isAdmin } },
},
pages: {
create: isEditor,
read: or(isAdmin, and(isStaff, ownPages)),
update: or(isAdmin, and(isEditor, ownPages)),
delete: isAdmin,
readVersions: or(isAdmin, and(isStaff, ownPages)),
fields: { internalNote: { read: isAdmin } },
},
"ab-experiments": { create: nobody, read: isStaff, update: nobody, delete: nobody },
"payload-kv": "payload-default",
"payload-locked-documents": "payload-default",
"payload-preferences": "payload-default",
"payload-migrations": { create: nobody, read: isAdmin, update: nobody, delete: nobody },
},
globals: {
settings: { read: anyone, update: isAdmin },
},
jobs: { run: isAdmin, queue: isAdmin, cancel: isAdmin },
plugins: {
ab: { duplicate: isEditor, manage: isAdmin },
},
allowedEndpoints: [
{ method: "get", path: "/health", reason: "Load balancer health check, returns no data" },
],
}) satisfies AccessPolicy<Config>;
payload generate:types normally ends payload-types.ts with declare module "payload" { interface GeneratedTypes extends Config {} }.
That block types Payload's slugs for every program that contains the file, and the policy brings the file into every program that imports payload.config.ts.
A program that imports the config and also builds other configs, such as integration tests with their own collections, then fails to type-check on every slug of its own.
Keep the block out of the generated file and give it its own file that only the app's tsconfig.json includes:
// payload.config.ts
typescript: { outputFile: path.resolve(dirname, "payload-types.ts"), declare: false },
// src/payload-generated-types.d.ts
import type { Config } from "./payload-types";
declare module "payload" {
export interface GeneratedTypes extends Config {}
}
The policy still imports Config from ./payload-types and is checked in every program that contains it, and the app keeps its typed Local API.
A test tsconfig that includes only its own folder does not pick up the .d.ts file.
Run payload generate:types after changing the option, and after adding a collection.
Apply it to the result of buildConfig:
// src/payload.config.ts
import { buildConfig } from "payload";
import { withAccessPolicy } from "@focus-reactive/payload-plugin-guard";
import { abPlugin } from "@focus-reactive/payload-plugin-ab";
import { accessPolicy } from "./access.policy";
export default withAccessPolicy(
accessPolicy,
buildConfig({
// ...
plugins: [abPlugin({ access: accessPolicy.plugins.ab })],
})
);
withAccessPolicy works on the sanitized config, so it also covers the collections Payload adds after the plugins have run.
Give Payload the config it returns.
An unchanged shallow copy ({ ...config }) also works; a copy with any key changed after the policy was applied stops the boot and names the changed keys, so make such changes inside buildConfig or in a plugin.
It does four things, in this order:
readVersions filter is rewritten for the versions collection, so it is written with the document's own field paths."payload-default" on a collection that is not Payload-internal; a hand-written access function left on a collection, global or field; a guarded plugin whose capabilities are missing from plugins or were given different gates; a plugin-locked operation that is not nobody; a guarded plugin whose name is a collection slug or starts with globals, because Payload routes those paths to the collection or to globals and never reaches the plugin's endpoints.onInit.Rules worth knowing:
admin; other collections cannot have it.readVersions.globals key; with globals, a missing key reports every global as missing."payload-default" keeps Payload's own access and is accepted only for payload-preferences, payload-locked-documents, payload-jobs, payload-kv, the folders collection and payload-query-presets.
Payload's defaults admit any signed-in user, so the guard also requires a panel user: a user of another auth collection is refused.
Query presets accept nothing else, because their access carries the per-preset sharing rules.
payload-migrations needs a real entry: Payload gives it no access of its own, which lets any logged-in user read it.
The global payload-jobs-stats, which Payload adds when a task or workflow has a schedule, needs { read: nobody, update: nobody }: the job scheduler reads and writes it through the database adapter, so no user needs it.
The boot error names the entry to write for both.layout.hero.secret is the field secret of the block hero in the blocks field layout, whether the block is inline or referenced by slug from config.blocks.
A block referenced by slug is one set of fields wherever it is used, so every entry that reaches one of its fields must give it the same gates.
Every block in config.blocks is audited for hand-written field access, including blocks only rich text uses.payload generate:types.A gate answers yes or no.
A filter answers yes, no, or a where that limits the documents.
Only a strict true allows; a gate that returns anything but a boolean, or a filter that returns an empty object, throws.
Payload reads any truthy result as "allow" on create, on field access, on admin and on jobs, so those take gates only.
A Gate is accepted wherever a Filter is, never the other way round.
| Helper | Result |
|---|---|
gate(({ req }) => boolean) | a gate |
filter(({ req, id, data }) => boolean | Where) | a filter |
and(...predicates), or(...predicates) | a gate when every input is a gate, otherwise a filter |
not(gate) | a gate |
forVersions(filter) | the filter with paths rewritten for the versions collection (title to version.title, id to parent) |
nobody | a gate that is always false |
anyone | a gate that is always true, for deliberately public reads |
panelUser | a gate that is true for a user of the admin user collection who may open the admin |
siteRender | a gate that is true only for a read made through site(payload), see Reads of the public site |
principalOf(req) returns who is calling: anonymous, foreign (a user of another auth collection, or one the admin collection's access.admin refuses) or panel, together with the channel (session, api-key, mcp).
panelUser is a floor, never a grant: low-role users and MCP agents are panel too.
The admin gate of the admin user collection cannot itself use panelUser.
import type { CollectionSlug } from "payload";
import { createGuardedPlugin, GuardError, project } from "@focus-reactive/payload-plugin-guard";
interface AbOptions {
collections: string[];
cronSecret?: string;
}
export const abPlugin = createGuardedPlugin<AbOptions, "duplicate" | "manage">({
name: "ab",
capabilities: ["duplicate", "manage"],
owns: () => ({ collections: ["ab-experiments"] }),
manages: (options) => options.collections,
setup: ({ config, options, guard }) => {
guard.endpoint({
kind: "panel",
capability: "duplicate",
method: "post",
path: "/duplicate",
input: (raw) => {
const { collection, id } = raw as { collection?: unknown; id?: unknown };
if (typeof id !== "string") {
throw new GuardError(400, "id is required");
}
return { collection: guard.slug(collection) as CollectionSlug, id };
},
handler: async ({ input, caller }) => {
const source = await caller.findByID({ collection: input.collection, id: input.id });
const { id: _id, ...data } = source;
const copy = await caller.create({ collection: input.collection, data });
return { id: copy?.id ?? null };
},
});
guard.endpoint({
kind: "machine",
secret: options.cronSecret,
method: "post",
path: "/rotate",
input: () => undefined,
handler: async ({ system }) => {
const running = await system("rotate running experiments").find({
collection: "ab-experiments",
});
return project(running, (result) => ({ rotated: result.totalDocs }));
},
});
return {
...config,
collections: [
...(config.collections ?? []),
guard.collection({
slug: "ab-experiments",
locked: ["create", "update", "delete"],
fields: [
{ name: "parent", type: "text", required: true },
guard.serverField({ name: "startedBy", type: "number" }),
],
hooks: { beforeChange: [guard.stamp("startedBy", ({ req }) => req.user?.id)] },
}),
],
};
},
});
A plugin name is lowercase letters, digits and dashes, because it is the prefix of every endpoint path.
The definition lists the slugs the plugin's system may touch:
owns: the collections and globals the plugin creates with guard.collection and guard.global.manages: the project's collections and globals the plugin reads and writes, the only slugs guard.slug accepts.reads: slugs the plugin's system may only read, such as the admin user collection; every write to them is refused.
It gets the options and the sanitized config, so reads: (_options, config) => [config.admin.user] names the admin user collection whatever the project called it.The project passes the gates from its policy; access is a required option with no default:
abPlugin({ collections: ["pages"], cronSecret: process.env.AB_CRON_SECRET, access: accessPolicy.plugins.ab });
withAccessPolicy checks that the plugin got exactly the gates in policy.plugins.ab.
A guarded plugin refuses to start when the config did not go through withAccessPolicy, on every init.
A factory that takes a type argument, like abTestingPlugin<TVariantData>(options), keeps it by annotating the exported constant; type arguments do not exist at runtime, so no cast is needed:
import { createGuardedPlugin, type GuardedPluginOptions } from "@focus-reactive/payload-plugin-guard";
import type { Plugin } from "payload";
const guarded = createGuardedPlugin<AbOptions, AbCapability>({ /* ... */ });
export const abTestingPlugin: <TVariantData extends object = object>(
options: GuardedPluginOptions<AbOptions<TVariantData>, AbCapability>
) => Plugin = guarded;
These are exported so a plugin can pass the facade or its pieces into helpers in other files:
| Type | What it is |
|---|---|
Guard<TCaps> | the guard facade given to setup; Guard<TCaps>["system"] types a stored guard.system |
GuardedPluginOptions<TOptions, TCaps> | the plugin's options with the required access |
HookArgs<H> | the arguments of a Payload hook type H plus caller and system |
HookTools | { caller, system } as hooks get them |
PanelHandlerArgs<I>, MachineHandlerArgs<I>, PublicHandlerArgs<I> | the arguments of an endpoint handler of each kind |
Caller, System<A> | the Local API wrappers |
guard.endpoint() registers the endpoint at the root, under /<plugin name>/, so the example above answers POST /api/ab/duplicate.
The guard never adds an endpoint to a collection or a global.
| Kind | Who gets in | Handler gets |
|---|---|---|
panel | 401 for anonymous, 403 for a foreign user, 403 for a channel not in channels (default ["session"]), then the capability gate | input, caller, system, principal, req, params, query |
machine | Authorization: Bearer <secret>, compared in constant time; an empty secret leaves the endpoint unregistered | input, system, req, params, query |
public | anyone | input, req, params, query |
POST, PUT, PATCH and DELETE need Content-Type: application/json and an input parser; the body is capped at maxBodyBytes (64 KiB by default).
The parser throws on invalid input and the request is answered with 400.input is what the parser returns, with no type arguments to write.
TypeScript reads an object from top to bottom, so the type reaches the handler only when input comes before handler; written after it, or left out on a GET, the handler gets unknown.
A parser that only passes the body on, input: (raw) => raw, gives unknown, and the handler then checks the shape itself.Response.GuardError(status, publicMessage) to choose the status and the message.
GuardError extends Payload's APIError, so thrown from a hook during a Payload REST or GraphQL request it is answered with its own status and message too.GET /<plugin name>/capabilities is registered for every plugin with capabilities and reserved: see Capability lookup for admin UI.| What happens | Level | Logged |
|---|---|---|
A 401 or 403 from a guarded endpoint: anonymous, foreign user, channel, capability gate, machine secret, or a GuardError/APIError with that status from the handler | warn | guard: { plugin, kind, endpoint, capability, status, reason, principal: { kind, channel, user: { collection, id } } } |
A 401 or 403 thrown inside guard.hook | warn | guard: { plugin, hook, status, reason, principal }, where hook names the collection or global, field and operation |
| A not-found answer or another 4xx | not logged | |
| Anything else thrown | error | the error |
Request bodies, headers, secrets and user emails are never logged.
A stream of refusals from one principal or address is what probing looks like.
withAccessPolicy sets Payload's own loggingLevels.GuardError to info unless the project set it, so Payload does not log a refused hook again as an error.
To count refusals, alert on them or send them to a store of your own, pass onRefusal as the third argument of withAccessPolicy:
export default withAccessPolicy(accessPolicy, buildConfig({ /* ... */ }), {
onRefusal: ({ status, plugin, method, path, principal, channel, reason, capability }) => {
metrics.increment("guard.refusal", { plugin, reason });
},
});
It hears every refusal the table above logs at warn, after it is logged.
reason is anonymous, foreign, channel, capability or secret when the guard refused the caller, and access for a 401 or 403 thrown inside a handler or a guarded hook.
principal is the principal's kind and channel its channel; the event carries no user, request, body or header, and it is frozen.
The listener cannot change the answer: the guard does not wait for it, and an error it throws or a promise it rejects is logged as an error while the request is still refused as before.
Every guarded plugin with capabilities answers GET /api/<plugin name>/capabilities with one boolean per capability of that plugin, for the user who asks:
// a client component of the ab plugin
const { routes } = useConfig().config;
const response = await fetch(`${routes.api}/ab/capabilities`, { credentials: "include" });
const can = (await response.json()) as { createVariant: boolean; splitTraffic: boolean };
Cache-Control: no-store.session gets 403, as on a panel endpoint.holdsCapability(req, { plugin, capability }) answers whether the request holds a capability of a guarded plugin, with the same checks as a panel endpoint: a panel user, on a listed channel (channels, default ["session"]), whom the plugin's gate from the policy admits.
Use it where no guarded endpoint runs: a server component of an admin view, a hook, or a check of a stored grant when the user it names comes back.
import { holdsCapability } from "@focus-reactive/payload-plugin-guard";
const canSeeSessions = await holdsCapability(req, { plugin: "analytics", capability: "viewSessions" });
false to anonymous callers, foreign users and other channels; it never throws for them.withAccessPolicy, because that is a mistake in the code, not an answer.caller and systemcaller runs the Local API as the requesting user, with overrideAccess: false; it does not accept overrideAccess, user or showHiddenFields.
findByID, update and delete throw the same NotFound, find returns an empty page and count returns zero.findByIDOrNull and findGlobalOrNull answer null instead of throwing when the document is missing or the caller may not read it, so a plugin never catches Forbidden or NotFound by hand.
findGlobal itself throws Payload's Forbidden when the policy refuses the read.create, update, duplicate and updateGlobal return the document as the caller may read it, or null.duplicate needs the caller's own read right on the source and create right on the collection; a source the caller cannot read throws the same NotFound as a missing one.update and delete take an id; delete returns { id }.caller.can("update", { collection, id }) answers with the caller's own right on that document.findVersions, findVersionByID and findGlobalVersions apply readVersions; a refused version throws the same NotFound as a missing one and a refused list is an empty page.restoreVersion needs the caller's own read right on the version and update right on the document, and returns the document as the caller may read it, or null.draft: true for any collection, including ones the plugin cannot type.system(reason) runs with access off, at depth 0 by default, and only on the slugs the plugin owns and manages, plus reads of the slugs it lists in reads.
Endpoint handlers and guard.hook get it bound to the plugin; guard.system(req, reason) gives the same system anywhere else in the plugin, such as a job handler, a hook added without guard.hook or a helper that only has req.
Its results are branded: an endpoint refuses to return them, or anything inside them, until they go through project(result, (value) => ...), which returns plain data.
The handler of guard.endpoint, route() and action() does not compile when its return type carries the brand, and the response is checked again at runtime; a return typed any, such as a React element, compiles and is still checked at runtime.
It has the same methods as caller except duplicate, can and findGlobalOrNull (findByIDOrNull answers null for a missing document), plus writes the Local API cannot express:
updatePublishedWithoutDraft({ collection, id, data }) sets fields on the published document of a collection with drafts and leaves its latest draft as it is, for example a value that must go live without publishing the editor's unfinished changes.
It takes only top-level, unlocalized, single-value scalar fields (text, textarea, email, number, checkbox, date, select, radio) and checks each value's type.
It writes the stored document through the database adapter: no hooks, no validation, no new version.
It returns false when the document has no published version.insertRow({ collection, data }), updateRowIf({ collection, id, where, data }) and deleteRows({ collection, where }) write rows of a collection the calling plugin owns and locks for that operation (create, update, delete), through the database adapter: no hooks, no validation, no versions, no access.
They are for stores only the plugin writes: an append-only log that a hook refuses to change, or a compare-and-set that must be one statement.
updateRowIf updates the row with id only while it also matches where, and returns null when it no longer does.
A collection that the calling plugin does not own, or whose operation it does not lock, is refused, even when another plugin owns and locks it.
Only the system of a guarded plugin writes rows: the standalone system(req, reason, slugs) refuses them.These and updatePublishedWithoutDraft are the guard's only database writes, so a plugin never needs payload.db.
Outside a plugin, the same functions are available as caller(req) and system(req, reason, slugs).
The standalone system has the same reads and writes on the slugs it is given, except row writes, because it belongs to no plugin that could own and lock a collection.
Their types are exported as Caller and System, for helpers that take them as an argument.
A site that renders next to Payload reads its content through the Local API, with no user.
Give those reads their own rule with the gate siteRender, and make them with site(payload):
// src/access.policy.ts
const published = filter(() => ({ _status: { equals: "published" } }));
// ...
pages: { read: or(isStaff, and(siteRender, published)), /* ... */ },
// the site's data layer
import { site } from "@focus-reactive/payload-plugin-guard";
const { docs } = await site(payload).find({ collection: "pages", where: { slug: { equals: slug } } });
siteRender is true for a read made through site(payload), and for the reads Payload makes on its behalf: the relations it populates and the hooks that pass its req on.req.payloadAPI === "local" or on a missing user admits the admin panel too.site() marks the read with an object only the guard holds, and no body, header or query equals it.site() reads with overrideAccess: false and refuses overrideAccess, req, showHiddenFields and disableErrors.
It has find, findByID, findByIDOrNull, count and findGlobal, and no writes.user, for example the signed-in editor of a draft preview: the read then gets what the policy gives that user or the site.siteRender only in read rules, and limit it to what every visitor may see, such as published documents: any server code that calls site() reads what it admits.site() reads outside the transaction of a request; a hook reads with caller(req) or system(req, reason, slugs).guard.collection() and guard.global() create the plugin's own collections and globals.
They take no access and no endpoints: access comes from the policy only.
A locked operation must be nobody in the policy, so nobody reaches it over REST or GraphQL and the plugin writes through system.
Consumer overrides add fields and hooks; they cannot remove plugin fields or set access.guard.serverField(field) closes create and update on a field, so only system writes it.guard.stamp(fieldName, ({ req, operation }) => value) is a beforeChange hook that overwrites the field on every write that carries a user.guard.slug(input) returns the slug when the plugin manages it, otherwise throws GuardError(400).
Its type covers collections and globals; narrow it when the plugin manages only collections.guard.hook(fn) turns fn into a Payload hook that also gets caller and system bound to the plugin.
The hook type comes from where the hook is placed (hooks: { afterChange: [guard.hook(...)] }) or is named: guard.hook<CollectionAfterChangeHook>(fn).
A hook written in another file types its arguments with HookArgs<CollectionAfterChangeHook>.route() and action() give a Next.js route handler and a "use server" action of the project the same checks as guard.endpoint.
The handler never gets payload: it gets caller, which acts with the rights of the request's user, and in every kind system(reason, slugs), the standalone system.
// src/app/(frontend)/next/preview/route.ts
import config from "@payload-config";
import { route } from "@focus-reactive/payload-plugin-guard";
import { redirect } from "next/navigation";
import { isEditor } from "@/access.policy";
export const GET = route({
config,
method: "GET",
kind: "panel",
gate: isEditor,
input: (raw) => ({ path: String((raw as { path?: unknown }).path ?? "/") }),
handler: ({ input }) => {
redirect(input.path.startsWith("/") ? input.path : "/");
},
});
// src/lib/search/search.ts
"use server";
import config from "@payload-config";
import { action } from "@focus-reactive/payload-plugin-guard";
import { headers } from "next/headers";
export const search = action({
config,
headers,
name: "search",
kind: "public",
input: (raw) => ({ query: String((raw as { query?: unknown }).query ?? "").slice(0, 200) }),
handler: async ({ input, caller }) => {
const pages = await caller.find({ collection: "pages", where: { title: { like: input.query } } });
return pages.docs.map((page) => ({ id: page.id, title: page.title }));
},
});
| Kind | Who gets in | Handler gets |
|---|---|---|
panel | a principal of the admin user collection on a channel in channels (default ["session"]) whom gate admits; 401 for anonymous, 403 otherwise | input, caller, system, principal |
machine | a request that presents secret, compared in constant time; an empty secret answers 404 | input, caller (anonymous), system |
public | anyone | input, caller (with the request's rights), system |
system(reason, slugs) is the same in every kind: access off, limited to slugs, results branded until project().
A public handler gets it too, because project code has no req to call system with otherwise, and a route that anyone may call still has work no visitor may do directly, such as provisioning the user of a verified sign-in.
Since anyone can trigger it, keep it to work whose outcome does not depend on who calls, and return only what project() lets through.config is the config withAccessPolicy returned, or the promise of it, such as the @payload-config import.
When Payload cannot start for it, the config did not go through withAccessPolicy, or its boot failed, a route answers a generic 500 and an action { ok: false, status: 500, error }, and the error is logged with console.error, since there is no Payload logger to use.gate is a gate, such as one from the policy file; anything else throws when the route or action is defined.request and the route's params.
method must match the request (a GET route also answers HEAD), or it answers 405.
POST, PUT, PATCH and DELETE need Content-Type: application/json and an input parser, and the body is capped at maxBodyBytes (64 KiB by default).
A GET parser gets the search parameters as an object.
A machine route reads the secret from Authorization: Bearer <secret>, or from token(request), for a link that carries it in the query, such as the preview link of Live Preview.headers (pass headers from next/headers), a name for the log, and an input parser for its one argument, capped at maxInputBytes (64 KiB by default, form data included).
A machine action reads Authorization: Bearer <secret>.
It answers { ok: true, data } or { ok: false, status, error }.onRefusal with plugin left out.redirect(), notFound() and the other errors Next throws to end a request (an error with a digest) pass through unchanged.system() result without project() answers 500, as in an endpoint.bun run check-security accepts a "use server" file whose every exported value is an action() call, without a security-allow comment.The census walks the config and classifies every endpoint as Payload core, made by the guard, or unregistered.
Payload core is every endpoint Payload registers itself, including those of optional features such as API key reveal (auth.useAPIKey.reveal) and orderable collections.
Core endpoints are recognised by handler identity against a reference config the guard builds; the handlers Payload creates anew for each config, such as the POST /reorder of orderable, are recognised by their place and their source text.
It fails when an unregistered root endpoint is not in policy.allowedEndpoints, or when any custom endpoint sits on a collection or a global, where it can shadow Payload's own routes.
A plugin that is not built on the guard registers its endpoints the same way your own code does, so each of them needs an entry.
Some appear only when an environment variable is set, and then the census fails on the deployment and not on your machine.
@payloadcms/storage-vercel-blob with clientUploads: true is one: with BLOB_READ_WRITE_TOKEN set it adds POST /vercel-blob-client-upload-route.
Read what the endpoint checks before you allow it, and write that down as the reason:
allowedEndpoints: [
{
method: "post",
path: "/vercel-blob-client-upload-route",
reason: "Vercel Blob client uploads; the storage plugin requires a signed-in user with create or update access to the upload collection",
},
],
It runs twice:
withAccessPolicy, so a config with an endpoint the census refuses never reaches Payload: the promise withAccessPolicy returns rejects, and every Payload init that awaits it fails.onInit, for the root endpoints added there.The endpoint lists cannot change outside these checks:
onInit of the config, and is frozen after it.onInit never runs, because Payload was started with disableOnInit or because Payload's development reload swapped it in, keeps the root list the first census checked.@payloadcms/next adds its Open Graph image route, GET /og, to the root endpoints on the first API request, which can come before or after the census.
The guard treats it as core when it arrives after withAccessPolicy and outside onInit, and lets it in after the census; it is the only change the frozen root array accepts.
Its handler cannot be imported from outside the Next.js bundle, so it is recognised by when it arrives and by its shape, not by identity.
A GET /og registered in the config or during onInit is classified like any other endpoint.
census(payload) returns the same report, with custom GraphQL queries and mutations, job tasks and workflows, and admin views.
When a boot check of the guard fails for a config, the config stays refused for the life of the process:
onInit on that retry.caller, system and holdsCapability throw that error for a request of that config; guarded endpoints, route() and action() answer it with a generic 500.The boot checks are the policy check, the census, the check that Payload got the config withAccessPolicy returned or an unchanged copy of it, and a guarded plugin's check that the config went through withAccessPolicy.
The guard repeats the last two, and refuses a config whose boot failed, when Payload sets up the database adapter, which every init does, also one that skips onInit.
A fixed config is a new config object, and the guard checks it anew.
safeEqual(a, b): constant-time string comparison.escapeHtml(text): escapes & < > " '.sandboxHeaders(allow?): Content-Security-Policy: sandbox and X-Content-Type-Options: nosniff, for responses that render user content.
allow lifts only scripts, forms, popups or modals (sandboxHeaders(["scripts"]) sends sandbox allow-scripts); the document always keeps an opaque origin, so its scripts never act as the CMS origin.publicUser(user, nameField): { id, name }, never the email.safeFetch(url, { allowedHosts, timeoutMs, privateHosts, ...init }): fetches only allowed hosts over http or https, refuses private, loopback and link-local addresses, and never follows redirects.
fetch cannot be pinned, safeFetch throws instead of fetching.timeoutMs (10 seconds by default) aborts the request and the reading of its body; the call then rejects with a TimeoutError, and a signal you pass still aborts it too.privateHosts: { hosts, reason } lets listed hosts resolve to private or loopback addresses, for a service the project runs on its own network, such as a local render service.
Each host must also be in allowedHosts, both lists come from the project's config, never from a request, and the reason (at least ten characters) says why, so the allowance is visible in review.
Redirects are still not followed, so an allowed private host cannot send the request anywhere else.Topics
Tags
payload plugin presets
Save and apply reusable block configurations as presets from the Payload admin blocks drawer
786.7k/wk37v3
payload plugin comments
Document-level and field-level comments with mentions, resolution and email notifications for Payload admin
757.0k/wk37v3
payload plugin ab
A/B testing with page variants managed in the Payload admin and routed by Next.js middleware at the edge
741.0k/wk37v3
payload plugin html preview
Live preview and click-to-edit in the Payload admin for any frontend that renders HTML, no framework needed
74451/wk37v3
payload plugin json form builder
Edit a Payload json field as real admin fields, with the form shape built in the admin panel
72441/wk37v3
payload plugin audit log
Append-only audit log of document, global and auth changes with CSV and NDJSON export
72394/wk37v3