Adds editorial workflows to Payload collections, defined in TypeScript as stages, actions, transitions, guards and effects. Editors get a stage indicator and drawer next to Save and Publish, plus a dashboard widget, while guards can block publishing until review is done across admin, REST, GraphQL and the Local API. It adds two collections for runs and history, and requires Payload 3.90+, React 19 and the companion guard plugin for access policy.
Editorial workflows for Payload CMS: stages, actions, transitions, guards and effects defined in code, run by people and agents alike
Installation
npm i @focus-reactive/payload-plugin-workflows37
Stars
5
Forks
33
Open Issues
Today
Last Updated
797
Weekly Downloads
v2.0.1
npm Version
1.1 MB
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 2 — 5 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-workflows)<a href="https://payloaddirectory.dev/plugins/1177993877-payload-plugin-workflows"><img src="https://payloaddirectory.dev/badge/1177993877-payload-plugin-workflows.svg" alt="Payload Directory"></a>README
Editorial workflows for Payload CMS, defined in TypeScript next to your collections and run by editors and AI agents alike.


| Stage indicator next to Save Draft and Publish | Dashboard widget: waiting on you, and a board per workflow |
|---|---|
![]() | ![]() |
Copy and paste this prompt into your AI assistant (Cursor, Claude, etc.) to integrate the plugin into an existing Payload project.
I want to add editorial workflows to my Payload CMS v3 project using
@focus-reactive/payload-plugin-workflows. Follow these steps in order, and stop to ask me where a step says so.
## Rules you must follow
- Never write an access rule that admits every logged-in user: no `Boolean(req.user)`, no `() => true`,
no `({ req }) => !!req.user`. A rule names a role, or it is `nobody`.
- Do not invent roles. Ask me which roles get each capability of the plugin.
- Write every policy entry by hand in `src/access.policy.ts`, and grant each capability and each
collection right explicitly to the roles I name. Nothing is open by default.
- When the boot or a request fails, fix the cause or ask me. Never use `anyone`, a looser gate,
`overrideAccess` or a removed or disabled check to make an error go away.
- Do not add `overrideAccess: true` anywhere, and do not add `access` to the plugin's collections.
## How it works
A workflow is written in TypeScript as stages (Draft → Review → Approved), each with the actions people
may take (Submit, Approve, Request changes) and transitions between stages. Editors get an indicator next
to Save / Publish that opens a drawer: the stages, whose turn it is, their action buttons and a history.
A "Workflows" dashboard widget shows what waits on each user. A stage's guard can hold publishing until
review is done (in the admin, REST, GraphQL and the Local API). Nothing is added to your collections; the
plugin adds two that only it writes: "workflow-instances" (runs, the read-only Workflows list in the nav)
and "workflow-events" (their history). Its endpoints live under /api/workflows/.
It declares four capabilities that the project grants in its access policy:
- `view`: see workflows (the drawer, the dashboard widget, GET /api/workflows/state and /history).
- `start`: start a workflow on a document. The caller also needs update rights on the document.
- `fire`: take a step in a workflow. The caller also needs update rights on the document.
- `abort`: stop a workflow. The caller also needs update rights on the document.
Who may read runs follows who may read their documents.
## Step 1: install
pnpm add @focus-reactive/payload-plugin-workflows @focus-reactive/payload-plugin-guard
Check that `payload` and `@payloadcms/ui` are 3.90 or later; if they are not, upgrade them first.
React 19 is required; `zod` 3.25+ or 4 only for the agent tools.
## Step 2: ask me about collections, stages and roles
Ask me which collections need a review, and which stages and steps it has, if that is not obvious.
Look at the auth collection named in `admin.user` and the roles it has. Ask me:
"Which roles may see workflows?", "Which roles may start a workflow?",
"Which roles may take steps in a workflow?" and "Which roles may stop a workflow?"
Wait for my answers. Write each answer as a gate in the policy file in step 4.
## Step 3: the workflow definition
Create src/workflows/editorialReview.ts. Replace 'posts' with the collection from my answer.
import { defineWorkflow, type CallerCondition } from '@focus-reactive/payload-plugin-workflows'
const notAuthor: CallerCondition = ({ actor, fields }) => actor.id !== fields.author // no self-review
export const editorialReview = defineWorkflow({
name: 'editorial-review',
title: 'Editorial review',
collections: ['posts'],
initialStage: 'draft', // no `start`: someone starts it from the drawer
requiredToPublish: 'approved', // every publish needs an approved review of that content
fields: [
{ name: 'author', type: 'user', initialValue: ({ actor }) => actor.id },
{ name: 'decision', type: 'string' },
{ name: 'reason', type: 'text' },
],
stages: [
{
name: 'draft',
title: 'Draft',
assignee: 'author', // only whoever started the run
actions: [{ name: 'submit', title: 'Submit for review', status: 'done' }],
transitions: [{ name: 'to-review', to: 'review' }], // no `when`: once submitted
},
{
name: 'review',
title: 'Review',
// roles: ['editor'], // if users have roles: only they may act here
actions: [
{ name: 'reset', when: () => true, set: { decision: null, reason: null } }, // automatic, on entry
{ name: 'approve', title: 'Approve', status: 'done', agents: 'deny', filter: notAuthor,
set: { decision: 'approved' } },
{ name: 'reject', title: 'Request changes', status: 'done', filter: notAuthor,
params: [{ name: 'reason', type: 'text', required: true }],
set: ({ params }) => ({ decision: 'rejected', reason: params.reason }) },
],
transitions: [
{ name: 'approved', to: 'approved', when: ({ fields }) => fields.decision === 'approved' },
{ name: 'back', to: 'draft', when: ({ fields }) => fields.decision === 'rejected' },
],
},
{ name: 'approved', title: 'Approved' }, // no transitions: entering it completes the run
],
})
defineWorkflow throws one error listing every problem with its path.
`requiredToPublish` and guards on 'publish' need drafts on the collection (versions: { drafts: true });
without them the plugin refuses the config.
## Step 4: the access policy file
Open `src/access.policy.ts`, or create it if the project has none, following the guard README
(`defineAccessPolicy`, `gate`, `filter`, `nobody`, `anyone`, checked with `satisfies AccessPolicy<Config>`).
If you create it, every collection and global of the config needs an entry: move each existing
`access` of the project into the file, and ask me for every rule you cannot read from the code.
Add these entries for this plugin:
import { readableWorkflowEvents, readableWorkflowRuns } from '@focus-reactive/payload-plugin-workflows'
collections: {
'workflow-instances': { create: nobody, read: readableWorkflowRuns, update: nobody, delete: nobody },
'workflow-events': { create: nobody, read: readableWorkflowEvents, update: nobody, delete: nobody },
},
plugins: {
workflows: {
view: <the gate from my first answer>,
start: <the gate from my second answer>,
fire: <the gate from my third answer>,
abort: <the gate from my fourth answer>,
},
},
## Step 5: register the plugin and wrap the config
// payload.config.ts
import { buildConfig } from 'payload'
import { withAccessPolicy } from '@focus-reactive/payload-plugin-guard'
import { workflowsPlugin } from '@focus-reactive/payload-plugin-workflows'
import { editorialReview } from './workflows/editorialReview'
import { accessPolicy } from './access.policy'
export default withAccessPolicy(
accessPolicy,
buildConfig({
// ...the existing config
plugins: [
// after any plugin that creates the collections the workflow names
workflowsPlugin({ workflows: [editorialReview], access: accessPolicy.plugins.workflows }),
],
})
)
Run `payload generate:importmap` and `payload generate:types`, then start the app.
A missing or wrong policy entry stops the boot with a list of what to fix.
Fix each item; never loosen a rule to make an error go away.
Postgres / SQLite with migrations: run `payload migrate:create add_workflows && payload migrate`.
Only if an action names effects: they run as Payload jobs on the "workflows-plugin" queue; add
jobs: { autoRun: [{ queue: 'workflows-plugin' }] } to the config, or run that queue from a cron.
## Step 6: verify, and show me the output
With the app running, send each request and show me the status code.
Every one of them must be refused. If one succeeds, the policy is wrong: stop and tell me.
1. Anonymous start, expect 401:
curl -i -X POST http://localhost:3000/api/workflows/start -H 'Content-Type: application/json' -d '{"workflow":"editorial-review","collection":"posts","id":"<post id>"}'
2. The same request with the session cookie of a user whose role may not start workflows, expect 403.
3. The same request as a user who may start workflows but may not update that post, expect 403 or 404.
4. Anonymous state read, expect 401:
curl -i 'http://localhost:3000/api/workflows/state?collection=posts&id=<post id>'
5. A write to the runs collection with an admin's session cookie, expect 403:
curl -i -X POST http://localhost:3000/api/workflow-instances -H 'Content-Type: application/json' -d '{}'
Then, as a user who may start workflows, open a post, press Workflow next to Save, Start workflow and
Submit for review. As another user press Publish: it is refused. Approve in the drawer and Publish goes
through. The dashboard shows the Workflows widget with the documents waiting on you.
Optional:
- MCP (@payloadcms/plugin-mcp): calls act as the API key's user, recorded as an AI agent.
import { workflowMcpTools } from '@focus-reactive/payload-plugin-workflows/agent'
mcpPlugin({ mcp: { tools: workflowMcpTools() } })
- payload-content-agent: contentAgentPlugin({ customTools: (ctx) => workflowAgentTools(ctx) }),
workflowAgentTools from the same /agent import. Both need zod.
- Multi-tenant projects: pass visibility: { fields, fromDocument, read } so runs follow the tenant; see
"Visibility and multi-tenancy" in the plugin README.
Editors see the run in a small indicator next to Save and Publish (a check and the final stage once it completed; just the dot or check on narrow screens). It opens a drawer laid out like Payload's document view: in the main column the stages, whose turn it is, what is on hold and the actions they may take (an action with params opens a short form in their place; when a person's step with params sent the run back, a banner says who and why); in the sidebar the key facts and the history. Stopping a workflow lives in the drawer's "⋮" menu, asks for confirmation and an optional reason. Status colours are the same everywhere: your turn (warning), in progress (neutral), completed (success), stopped (muted), stuck (error). Agents use the same operations through a set of tools.
// src/workflows/editorialReview.ts
import { defineWorkflow } from "@focus-reactive/payload-plugin-workflows";
export const editorialReview = defineWorkflow({
name: "editorial-review",
title: "Editorial review",
collections: ["pages"],
initialStage: "drafting",
fields: [
// Whoever starts the run: the author owns the drafting and never reviews their own work.
{ name: "author", type: "user", initialValue: ({ actor }) => actor.id },
{ name: "reviewer", type: "user" },
{ name: "decision", type: "string" },
{ name: "reason", type: "text" },
],
stages: [
{
name: "drafting",
title: "Drafting",
assignee: "author",
actions: [{ name: "submit", title: "Submit for review", status: "done" }],
// No `when`: leaves once the stage's actions are done.
transitions: [{ name: "to-review", to: "review" }],
},
{
name: "review",
title: "Review",
guards: [{ name: "hold", title: "A reviewer must approve this page first.", operations: ["publish"] }],
assignee: "reviewer", // once set, only that user may act
roles: ["editor"], // until then, anyone with this role
actions: [
// Automatic (`when`): on entering the stage, clear the previous round's decision.
{ name: "reset", when: () => true, set: { decision: null, reason: null } },
{ name: "claim", title: "Take this review",
filter: ({ actor, fields }) => !fields.reviewer && actor.id !== fields.author,
set: ({ actor }) => ({ reviewer: actor.id }) },
{ name: "approve", title: "Approve", status: "done", set: { decision: "approved" },
filter: ({ actor, fields }) => actor.id !== fields.author, effects: ["notify-author"] },
{ name: "reject", title: "Request changes", status: "done",
filter: ({ actor, fields }) => actor.id !== fields.author,
params: [{ name: "reason", type: "text", required: true }],
set: ({ params }) => ({ decision: "rejected", reason: params.reason }) },
],
transitions: [
{ name: "approved", to: "approved", when: ({ fields }) => fields.decision === "approved" },
{ name: "back", to: "drafting", when: ({ fields }) => fields.decision === "rejected" },
],
},
{ name: "approved", title: "Approved" }, // no transitions: entering it completes the run
],
});
defineWorkflow validates the definition and throws one error listing every problem with its path (stages[1].transitions[0].to: transition target "ready" is not a declared stage…).
Requires Payload 3.90+, Next.js 15 or 16 and React 19; zod (3.25+ or 4) only for the agent tools.
The plugin is built on @focus-reactive/payload-plugin-guard: the project's access lives in one policy file, and the config is wrapped with withAccessPolicy.
pnpm add @focus-reactive/payload-plugin-workflows @focus-reactive/payload-plugin-guard
Grant the plugin's capabilities and give its two collections their entries in your access policy:
// src/access.policy.ts
import { defineAccessPolicy, gate, nobody } from "@focus-reactive/payload-plugin-guard";
import { readableWorkflowEvents, readableWorkflowRuns } from "@focus-reactive/payload-plugin-workflows";
const hasRole = (...roles: string[]) =>
gate(({ req }) => req.user?.collection === "users" && roles.some((role) => req.user?.roles?.includes(role)));
export const accessPolicy = defineAccessPolicy({
collections: {
// ...your collections
"workflow-instances": { create: nobody, read: readableWorkflowRuns, update: nobody, delete: nobody },
"workflow-events": { create: nobody, read: readableWorkflowEvents, update: nobody, delete: nobody },
},
globals: {},
plugins: {
workflows: {
view: hasRole("admin", "editor", "author"),
start: hasRole("admin", "editor", "author"),
fire: hasRole("admin", "editor", "author"),
abort: hasRole("admin", "editor"),
},
},
});
// payload.config.ts
import { withAccessPolicy } from "@focus-reactive/payload-plugin-guard";
import { workflowsPlugin } from "@focus-reactive/payload-plugin-workflows";
import { accessPolicy } from "./access.policy";
import { editorialReview } from "./workflows/editorialReview";
export default withAccessPolicy(
accessPolicy,
buildConfig({
plugins: [
workflowsPlugin({
workflows: [editorialReview],
access: accessPolicy.plugins.workflows,
effects: { "notify-author": async ({ payload, instance }) => payload.logger.info(instance.subject?.title) },
}),
],
})
);
Then run pnpm payload generate:importmap, and on SQL databases without push create a migration (the plugin adds the workflow-instances and workflow-events collections and two jobs tasks).
The plugin adds, to each collection a workflow names, the indicator (admin.components.edit.beforeDocumentControls) and the hooks; it adds no fields to them. It also adds the runs collection, the endpoints, two jobs tasks, a dashboard widget and the admin strings. The components are referenced through the import map (/client for client components, /rsc for server ones), hence generate:importmap.
On the dashboard, a Workflows widget (Payload's modular dashboard, admin.dashboard.widgets): first Waiting on you (up to five documents waiting on you or one of your roles, then those open to anyone, each with its stage and how long it has waited), then a board per workflow with open documents (one column per stage, its count and the first three documents). It reads with the viewer's access, like the API below, and shows only to users with the view capability. Without a defaultLayout of yours it comes first, above Payload's collection cards; with one (an array, or a function) it is appended to it. Payload keeps a layout per user once they save one in the dashboard's edit mode; those users add Workflows from Add there (or Reset layout).
The full list is Payload's own list view of the runs collection, Workflows in the nav (for users of the admin user collection, each seeing only workflows on documents they may read): document, workflow, stage, status, who it waits on, last change, with Payload's filters and sorting. It is read-only (nobody can create, edit or delete a run) and a row opens its document, where the drawer shows and moves the workflow. The widget's View all opens it filtered to open workflows (?where[status][equals]=active).
To try it: save a page, press Workflow next to Save, Start workflow and Submit for review; as another user, Take this review and press Publish: it is refused ("Publishing is on hold. A reviewer must approve this page first."). Approve completes the run and publishing goes through.
actions, with optional assignee and roles. A stage without transitions is terminal: entering it completes the run.set, an object or a function of the context), mark the stage's task finished (status: "done" | "skipped" | "failed"), ask the caller for input (params: string, text, number, boolean, date, select), narrow who may fire it (roles, filter, agents: "deny" for a step only a person may take) and queue effects. An action with when is automatic: the engine fires it as soon as the condition holds, at most once per stage visit, and nobody can call it.when holds moves the run. Without when a transition opens once the stage's task is done or skipped. This repeats until nothing moves (at most 50 steps, against definitions that loop).string, text, number, boolean, date, user, json; every write is type-checked (invalid-patch otherwise) and null unsets. initialValue seeds a field: a value, or a function of the start (({ actor, doc }) => value, e.g. actor.id to hold who started it; unset when the system starts it); only fields with input: true may be passed when starting (startWorkflow({ fields })).publish, update, delete) are refused with what is on hold and the guard's title ("Publishing is on hold. A reviewer must approve this page first."), unless its unless condition holds. A workflow that starts on create is checked before the insert: creating a document already published is refused when the stage it would start in holds publish. It is enforced in collection hooks, so it holds for the admin, REST, GraphQL and the Local API. publish needs drafts on the collection (the plugin refuses the config otherwise) and covers publishing a draft, any non-draft save of a published document and, with a status per locale, any non-draft save; moving to the trash counts as delete. To let one write through, see the two request flags below.effects, run as a Payload job queued in the same transaction as the change. It gets { payload, req, instance, doc, effect } and may return { set } to write fields and move the run. The set lands only while the run is still in the stage visit that queued the effect (effect.stage, effect.visit); if the run has moved on, or left and come back, the outcome is recorded as finished with its result ignored. A handler that throws is retried, so it runs at least once and may run again: make it idempotent. Recording a successful outcome retries on its own and never runs the handler again. With jobs.enableConcurrencyControl: true in your Payload config, the effects of one run are also run one at a time.assignee field holds a user, only that user may act. Otherwise anyone with one of the roles may, or anyone at all without roles. Roles come from user.roles or user.role unless you pass roles.admin.user). A user field, an assignee and an actor are ids of that collection. A user of any other auth collection (API clients, customers) is refused every operation and every read with not-allowed, whatever the gates or rules return: they can narrow who takes part, never widen it, so user 5 of customers is never mistaken for user 5 of users. An MCP plugin whose userCollection is another collection gets the same refusal on every workflow tool. Saves by such users still settle runs and pass guards as anyone's; the history records them as the system.when, filter, skipIf, guard unless, start.when, initialValue, visibility.fromDocument) sees the document in the project's default locale, with Payload's usual fallback, whoever saves it in whichever locale. A save in another locale is read again in the default locale (only when a run is active, a workflow may start, or visibility values may have changed); a guard on a localized field is judged on its default-locale value. Editing a translation alone never moves a run.when, unless, filter, skipIf) are synchronous functions of { fields, activities, allActivitiesDone, anyActivityFailed, doc, now, stage }; doc is the latest draft. A filter also sees the caller (actor, roles, assigned). A condition that throws fails the operation and nothing is written.requiredToPublish on a workflow names the terminal stage (or stages) that approve, and makes the workflow a gate: every publish of a document it covers needs a run of it that completed in one of those stages and that no publish has used yet, and the publish uses it. requiredToPublish: "approved", or ["approved", "approved-with-edits"] for several approving endings; each must be a declared stage with no transitions (true / false are refused with a pointer to this form). A run that ended in another terminal stage (say rejected) counts as none. Refused otherwise, with what to do: no run or a stopped one, "Publishing requires a completed Editorial review. Start it from the Workflow button."; one in progress, "Publishing requires a completed Editorial review; it is in progress."; one that ended in a stage that does not approve, "The Editorial review ended without approval (Rejected). Publishing requires a new Editorial review; start it from the Workflow button."; the last one already used, "This version was approved and published; changes need a new Editorial review.". It uses the guards' publish detection (publishing a draft, creating a document published, a non-draft save of a published document); draft saves, autosave, unpublishing, trash and delete are never refused. The approval is bound to the content: a run that completes in an approving stage records the document's latest version, and a publish is refused ("The document changed after the Editorial review approved it; publishing it needs a new Editorial review.") when the latest version is not that one, or when the publish itself changes the content. The run records published and keeps the time (publishedAt). Several required workflows on one collection must all be completed, and are all used. The bypass flag lets a refused publish through and records guard-bypassed (guards ["requiredToPublish"]) on the latest run, if there is one. Needs drafts on the collection (the plugin refuses the config otherwise). The indicator and the drawer say "Required before publishing", that the review approved it and it is ready to publish (the indicator: "Ready to publish") or, once used, that further changes need a new workflow; a run that ended without approval shows as completed in the drawer, with a quiet note that it does not allow publishing, and the indicator is back to "Required before publishing"; Payload's Publish button stays as it is and a refused publish shows the message above.start a person (or agent) starts a run from the drawer or the API. start: { on: "create", when?: ({ doc }) => boolean } starts one when a document is created (and when, if given, holds for it). A document runs at most one active run of a workflow.title: { en: "Review", de: "Prüfung" }. Views resolve them for the request's language, else English, else the first given.string or text param takes at most 5,000 characters (TEXT_MAX_LENGTH), or its own maxLength; a stop reason at most 5,000. Longer input is refused with invalid-params: it would be kept in the history for good.version if you declare one (a string or number), else a short hash of the definition's structure (names of stages, activities, actions, transitions and fields, transition targets, field types; not titles, descriptions or functions). When the code's version differs from a run's, the drawer says so in one quiet line.Activities: when a stage has several parallel tasks. Instead of actions, a stage may declare activities: [{ name, title, assignee, roles, skipIf, actions }], each finished separately by an action's status; the default transition waits for all of them. An activity's skipIf is evaluated once, on entering the stage: true skips it for that visit (an action's filter, by contrast, decides every time whether a caller may fire it). Plain stage actions are exactly one activity named after the stage, so the two forms behave the same; a stage uses one or the other. When firing an action in a stage with several activities, name the activity.
| Option | Default | What it does |
|---|---|---|
workflows | - | The workflows. Names must be unique; their collections must exist |
effects | {} | Effect handlers by name; every effect an action names must be registered |
roles | user.roles / user.role | (user) => string[]: a user's roles, for assignment |
access | required | { view, start, fire, abort }: the gates from your access policy, accessPolicy.plugins.workflows. See Access and capabilities |
rules | none | { start?, fire?, abort? }, each ({ req, user, workflow, collection, id, doc, stage?, activity?, action?, run? }) => boolean: narrower rules per run, on top of the capability and the document right. user is the user the operation acts for; only true allows; a rule that throws fails the operation with a generic error. fire also gets the run's stage, the activity (named, or the stage's only one), the action and the run ({ id, fields }); abort the stage and run. Without abort: while a guard holds, only someone who may act in the stage may stop the run, so stopping is never a way around a hold |
documentAccess | update for each | { start?, fire?, abort? }, each "update" or "read": the right on the document the caller needs besides the capability. "read" lets someone who may only read a document take part in its workflow, e.g. a reviewer who approves but never edits |
visibility | - | { fields, fromDocument, read }: who sees which workflows, from facts kept on the runs. See Visibility and multi-tenancy |
dashboard | true | false leaves the dashboard alone (no widget) |
enabled | true | false keeps the runs collection (its data and schema) and the job tasks, so queued effects still run; it leaves out the hooks and guards, the endpoints, the admin components and the widget |
Every operation acts as user, which is required (unauthorized without one), and reads the document with that user's access: someone who cannot read a document can neither see nor move its workflow.
The reads need the view capability; starting, firing and aborting need their capability and the document right from documentAccess, then rules may narrow further (see Access and capabilities).
import { abortWorkflow, fireWorkflowAction, getWorkflowHistory, getWorkflowState,
listWorkflowInstances, startWorkflow } from "@focus-reactive/payload-plugin-workflows";
const run = await startWorkflow(payload, { workflow: "editorial-review", collection: "pages", id, user });
await fireWorkflowAction(payload, { instanceId: run.id!, action: "submit", user });
await fireWorkflowAction(payload, { instanceId: run.id!, action: "reject", params: { reason: "Too long" }, user });
await abortWorkflow(payload, { instanceId: run.id!, reason: "Duplicate", user });
const { instances, available } = await getWorkflowState(payload, { collection: "pages", id, user });
const inbox = await listWorkflowInstances(payload, { scope: "mine", status: "active", user }); // waiting on you first, then open to anyone
const older = await getWorkflowHistory(payload, { instanceId: run.id!, before: run.olderHistory + 1, user }); // { entries, older }
fireWorkflowAction takes activity only when the stage has several. The operations return an InstanceView: the stage, the stepper (each stage current, visited or unvisited in this run) with allowed and reason (from the same check fire runs, so an enabled button never fails for a reason the UI could have known; for a caller without the fire capability or the document right documentAccess.fire, every action of an active run is not allowed, with reasonCode: "access"), the guards holding, who it waits on (user ids and roles), whether the caller may stop it (canAbort), the fields, who started it (started), the definition version it started from and whether the code's differs (definitionVersion, definitionChanged), and the most recent 50 history entries (history), with the count of older ones (olderHistory). Entries are numbered per run (seq: 1, 2, … without gaps), so getWorkflowHistory({ before: seq }) reads the page before any entry, one indexed read whatever the history's length. getWorkflowState returns a document's active runs and its latest finished one. listWorkflowInstances pages, sorts and counts in the database, with the caller's read access, so runs on documents the caller cannot read are neither listed nor counted. The reads take the caller's req ({ …, req }) so access rules that read its headers or cookies see them. Without visibility, when runs are hidden because a per-document read rule allows more than 5,000 documents, the answer says so in hiddenCollections. With a workflow requiredToPublish on the collection, getWorkflowState also answers publish: { clear, reason? } (the check a publish would get), the runs carry requiredToPublish (the approving stage names: a completed run whose stage is not among them does not allow publishing) and publishedAt, and available entries requiredToPublish.
A refusal throws WorkflowError with a code (isWorkflowError narrows it): unauthorized, not-allowed, invalid-params, invalid-patch, already-running, conflict, instance-not-active, activity-not-active, not-callable, or unknown-workflow / -instance / -subject / -stage / -activity / -action. Concurrent changes to one run use optimistic locking: the loser re-runs on fresh state, and after three attempts it is conflict.
The same operations are endpoints under your API route, described in Access and capabilities below.
Runs themselves are readable over Payload's own REST and GraphQL API for the workflow-instances collection, and their history for workflow-events, with the read rule your policy gives them (readableWorkflowRuns and readableWorkflowEvents): like the list view, a caller sees only the runs they may see (see below).
Nobody can create, update or delete either collection over REST, GraphQL or the Local API; only the plugin writes them.
| Capability | Lets a user | Also needs, on the document |
|---|---|---|
view | see workflows: the drawer, the dashboard widget, the state, history and list reads | read |
start | start a workflow | documentAccess.start, update by default |
fire | take a step: an action of a stage they may act in | documentAccess.fire, update by default |
abort | stop a workflow | documentAccess.abort, update by default |
The capability says who may act at all.
The document right comes from the policy entry you already wrote for the document's collection.
Assignment, roles, an action's filter and your rules then decide each step, as before.
The admin follows the same checks: a user without view sees no workflow indicator on documents, and a user without fire or the document right documentAccess.fire sees no action buttons and is never told a run waits on them.
Only users of the admin user collection take part; a user of any other auth collection is refused, whatever the gates say.
The same checks apply to the Local API functions, the agent tools and the endpoints.
| Endpoint | Capability | Body or query |
|---|---|---|
GET /api/workflows/state | view | ?collection=&id=, answers like getWorkflowState |
GET /api/workflows/history | view | ?instanceId=&before=&limit=, answers like getWorkflowHistory |
POST /api/workflows/start | start | { workflow, collection, id, fields? } |
POST /api/workflows/fire | fire | { instanceId, action, activity?, params? } |
POST /api/workflows/abort | abort | { instanceId, reason? } |
GET /api/workflows/capabilities | { view, start, fire, abort } for the signed-in user, so custom admin UI can hide controls; the server still checks every call |
workflows would hide them, so the guard refuses such a config at boot.
Anonymous callers get 401; users of another auth collection and users without the capability get 403.Content-Type: application/json (415 otherwise) and at most 64 KiB; names and ids are at most 256 characters, fields and params at most 50 entries.{ error, code } with 401, 403, 400, 404 or 409 by code; a document or run the caller may not see is 404.
Any other error answers a generic 500, and the details go to the server log.| Slug | Written by | Read by |
|---|---|---|
workflow-instances | the plugin only | your policy's read: readableWorkflowRuns |
workflow-events | the plugin only | your policy's read: readableWorkflowEvents |
Without configuration a run is visible to whoever may read its document: each subject collection's own read access decides (false: none of its runs; true: all; a query constraint, i.e. a per-document rule: the runs on the ids it allows, resolved once per request with one query of at most 5,000 ids; above that the collection's runs are hidden from that user, a warning is logged once, and the plugin's lists, document state and dashboard widget say that some workflows are hidden). That is correct with nothing to set up, and fine for small sites.
Configure visibility when a subject collection has a per-document read rule over many documents, which is always the case with multi-tenancy (a tenant user's read is a query on the tenant). You say which facts about a document decide who may see its workflows, the plugin keeps them on the runs, and visibility is one ordinary Payload access rule over them, applied by the database: no ids resolved, no cap, no hiddenCollections.
visibility: {
fields: [{ name: "tenant", type: "relationship", relationTo: "tenants", index: true }], // added to the runs, read-only
fromDocument: ({ doc, collection, req }) => ({ tenant: doc.tenant }), // sync and pure; a populated relationship is stored as its id
read: ({ req }) => …, // a normal access function over those fields
}
WORKFLOW_SKIP.fromDocument throws for the saved document, or writing the new values fails, and the document has runs, the save is refused with a 500, "The document was not saved: its workflow visibility could not be updated…", and nothing of it is kept (a document without runs saves normally; the error is logged). A start whose fromDocument throws fails, and no run is created; for the automatic start on create, the document is saved without the run.run is a relationship, and read applies to events through it ({ tenant: … } reads run.tenant). Nothing is copied onto events, so they stay append-only.read is not plainly false for them and read allows the run. read returning false shows nothing (an empty list, not a 403).visibility decides who sees runs and their history (lists, the widget, the runs list view, REST, GraphQL, counts). Acting is unchanged: starting, firing, stopping and the document's state still read the document with the caller's own access first, and the capabilities, document rights and rules decide.With @payloadcms/plugin-multi-tenant, its getTenantAccess (from @payloadcms/plugin-multi-tenant/utilities) builds exactly the rule over the runs' own tenant field:
import { multiTenantPlugin } from "@payloadcms/plugin-multi-tenant";
import { getTenantAccess } from "@payloadcms/plugin-multi-tenant/utilities";
const allTenants = (user) => Boolean(user?.roles?.includes("super-admin"));
plugins: [
workflowsPlugin({
workflows,
visibility: {
fields: [{ name: "tenant", type: "relationship", relationTo: "tenants", index: true }],
fromDocument: ({ doc }) => ({ tenant: doc.tenant }),
read: ({ req: { user } }) => allTenants(user) || getTenantAccess({ fieldName: "tenant", user }),
},
}),
multiTenantPlugin({ collections: { pages: {} }, userHasAccessToAllTenants: allTenants }),
];
Use a plain relationship field as above, and do not list workflow-instances or workflow-events in the multi-tenant plugin's collections: its tenant field takes its value from the editor's tenant cookie and validates the writer's tenants, while runs are written by the plugin from the document. Pass the same userHasAccessToAllTenants to both, as it is not part of getTenantAccess. What visibility does not do: it does not change who may read the documents themselves, does not filter by the tenant selected in the admin (the runs list shows all of a user's tenants), and does not decide who may act.
History and audits. A run's history is the workflow-events collection: one row per entry, inserted in the same transaction as the run's change (or not at all), never updated. Columns: run (a relationship to the run, never populated), seq, type (started, action, transition, effect, completed, aborted, guard-bypassed, published; a later version may add types: treat unknown ones as such, isKnownEvent narrows), at, workflow, subjectCollection / subjectId (copied, so an audit needs no join), stage, who (actorId, a user of the admin user collection, and via; none on the system's entries), cause (on the system's entries: step (a person's or agent's step in the same operation), save, delete, start, tick, effect), activity, action, transition, toStage, effect, status and detail (params, a reason, an error, the effect's Payload job id, who saved…). It is hidden from the admin nav and read-only over REST, GraphQL and the Local API, with the same rule as runs: an event is readable exactly when its run is. For example:
const events = (where: Where) => payload.find({ collection: "workflow-events", where, sort: "-at", user, overrideAccess: false });
// Who approved which page last month?
await events({ and: [{ workflow: { equals: "editorial-review" } }, { type: { equals: "action" } }, { action: { equals: "approve" } },
{ at: { greater_than_equal: "2026-10-01" } }, { at: { less_than: "2026-11-01" } }] }); // actorId, subjectId, at
// What was written past a hold (e.g. published without review)? `detail.operation` says which write.
await events({ type: { equals: "guard-bypassed" } });
// Everything agents did this week.
await events({ and: [{ via: { equals: "agent" } }, { at: { greater_than_equal: weekAgo } }] });
Retention. Nothing is deleted on its own: stopping a run, or deleting its document, keeps its history (the audit trail). pruneWorkflows(payload, { finishedBefore: date }) deletes finished runs (completed or stopped) that finished before date, with their events, in batches of 200 runs, each in its own transaction, and returns { runs, events }; active runs are never touched. Call it from your own schedule with the retention you need.
Request flags, set on a Local API call's context (never on a shared req): context: { [WORKFLOW_BYPASS]: true } lets the write through the guards, for example an effect that publishes as part of the workflow; when a guard would have held it, the run records a guard-bypassed entry with the operation and who wrote. context: { [WORKFLOW_SKIP]: true } makes the hooks neither start nor settle runs for that write (seeding, imports); guards still apply unless the bypass flag is set too, and deleting a document still stops its runs.
Testing. createWorkflowSimulator(definition, { doc }) runs a definition in memory on the same engine, without Payload: sim.fire("submit", { user: "ann" }), sim.fire("reject", { user: "bea", roles: ["editor"], params: { reason: "Too long" } }), then assert on sim.state.stage, sim.view(caller), sim.events, sim.effects. It also has setDoc(doc), advance(date), patch(fields) and abort(reason, who?).
Conditions that read now. The plugin re-checks a document's runs on every save, but nothing re-checks them as time passes. If a condition reads now, call tickWorkflows(payload) from your own schedule, or queue the workflowsPluginTick task on one. It settles the active runs whose stage can move without a write (one with an automatic action or a transition with its own when), reading their documents a page at a time.
An agent can do exactly what the user behind its token can do (same capabilities, access rules, assignments, roles and filters as in the admin), and every step it takes is marked as an agent's in the history (via: "agent").
A call that comes in through MCP counts as an agent's whatever path it takes, so agents: "deny" holds for the endpoints too.
Text that people wrote (field values, step parameters, reasons, document titles) reaches the agent fenced as untrusted, with untrustedText in the result saying so, and a failure other than a workflow refusal answers a generic error. Five tools: workflows_list_definitions, workflows_list_instances, workflows_get_state, workflows_start, workflows_fire_action. They answer a refusal with { error, code } instead of throwing. Two ways in, both from @focus-reactive/payload-plugin-workflows/agent (needs zod):
AI-SDK tools, for payload-content-agent or any AI SDK agent; they act as user:
import { workflowAgentTools } from "@focus-reactive/payload-plugin-workflows/agent";
contentAgentPlugin({ customTools: (ctx) => workflowAgentTools(ctx) }); // ctx: { payload, user }
MCP tools, for any MCP client through @payloadcms/plugin-mcp; a call acts as the user the MCP API key belongs to:
import { workflowMcpTools } from "@focus-reactive/payload-plugin-workflows/agent";
import { mcpPlugin } from "@payloadcms/plugin-mcp";
plugins: [workflowsPlugin({ workflows }), mcpPlugin({ mcp: { tools: workflowMcpTools() } })];
Each tool appears under the API key's "Tools" settings (workflowsListDefinitions, …) on by default for a new key, and can be switched off per key. The result is the tool's answer as JSON text, with isError: true on a refusal.
Reserving a step for a person. agents: "deny" on a caller action makes it unavailable to agents, whoever's token they hold; people see no difference. An agent gets the action back from workflows_get_state as not allowed, with reasonCode: "agents" and "This step is reserved for a person.", and firing it is not-allowed. For example, the final approval:
{ name: "approve", title: "Approve", status: "done", agents: "deny", set: { decision: "approved" } }
Read in this order:
src/types.ts: the vocabulary (definition, run state, view).src/define.ts: defineWorkflow: validation, and plain stage actions turned into one activity.src/engine/engine.ts: the pure engine: start, fire, abort, and settle (the cascade). No Payload.src/engine/view.ts: what a caller sees and may do, from the same verdict as fire.src/server/operations.ts: start, fire, abort and settle against Payload: access, the document, the answer.src/server/store.ts: the runs collection and its two writes (create, compare-and-swap update), each inserting the step's events and queueing its effects in the same transaction; pruneWorkflows. src/server/events.ts: the events collection. src/server/access.ts: the read rule of both collections (with or without visibility). src/server/visibility.ts: the runs' visibility values. src/server/publishing.ts: requiredToPublish.src/server/effects.ts: the effect job. src/hooks.ts: guards and settle-on-save. src/endpoints.ts: REST, through the guard. src/server/guarded.ts: the plugin's system access, limited to its collections and the workflows' subjects. src/agent.ts: the five agent operations, once, as AI-SDK and MCP tools.src/components/: the indicator and drawer (document/), the dashboard widget (widget/, a server component) and the list's cells (list/).One action, from the button to the database: the drawer posts to /api/workflows/fire → the guard checks the session and the fire capability → endpoints.ts → fireWorkflowAction in server/operations.ts checks the capability and the document right, reads the run and the document as the user and checks rules.fire → mutateRun in server/store.ts calls fire on the run just read in engine/engine.ts, which checks the verdict and params, applies the action, settles and returns the new state with the step's events → the new state is written only if revision is unchanged, then its effect jobs and its events → the operation runs the effects if it owns the commit and answers with the view (the run and its latest 50 events).
req with an open transaction; a save that settles or starts a run while database transactions are on) its job waits for a jobs runner on the workflows-plugin queue: configure jobs: { autoRun: [{ queue: "workflows-plugin" }] }. The plugin warns once at startup if effects are declared and nothing covers the queue. With jobs.runHooks: true, Payload 3.90 fails to record a successful task, so the job can run again.| is not supported; % and _ in a role or id match like SQL wildcards, and matching is case-insensitive, so such a role may list a few runs too many (who may act is still checked exactly).visibility.fromDocument throwing on a document with runs, which fails the save (see Visibility and multi-tenancy). If a run write fails in the database (Postgres aborts the whole transaction on any statement error), or a Payload operation the hook calls throws (Payload then rolls back the request's transaction, on any adapter with transactions on), the save's changes are already lost: the save fails with a 500, "The document was not saved: its workflow could not be updated…", and the cause is logged. Likewise startWorkflow with your req that loses a race for the same document rolls back your transaction, and its already-running error says so. Under normal load none of this happens: concurrent writers are refused by revision and retried, not errored. SQLite can reuse a deleted document's id, so an old run can end up on a new document. Serialization failures under stricter isolation levels are not retried.run_seq_idx and subjectCollection_subjectId_idx share the schema's namespace with your collections' compound indexes; a collection of yours with a compound index on the same field names would clash.requiredToPublish and Payload's other ways to publish. Scheduled publishing runs as the user who scheduled it and goes through only if a completed, unused run exists when it fires (else the job fails with the refusal). Bulk publish from the list view checks and uses each document's run separately; the others fail with the message. Restoring a published version (not as a draft) is a publish; restoring one as a draft is also treated as a publish, because Payload hands the hooks the version's published status (the guards behave the same). Publishing one locale uses the approval: the next locale needs a new run. Duplicating a published document through the Local API without _status: "draft" creates it published, so it is refused (the admin's Duplicate makes a draft). Without database transactions, a publish that fails after the hook still used the run.2.0 moves the plugin onto @focus-reactive/payload-plugin-guard; Upgrading to the guard explains the model all the plugins share, with a complete example.
Every access rule is now written by hand in your project's src/access.policy.ts, and nothing is open by default: an entry you leave out stops the boot, and a capability you do not grant is refused for everyone.
@payloadcms/* package 3.90 or later, with the React and Next versions Payload 3.90 requires, Node 22.22 or later, and @focus-reactive/payload-plugin-guard installed next to the plugin.access holds four capabilities from the policy and has no default; the narrowing callbacks that were access: { start, fire, abort } are now rules: { start, fire, abort }, with the same arguments.documentAccess: { fire: "read" } (or start, abort) where people who may only read a document should take part in its workflow./api/workflow-instances/{state,history,start,fire,abort} to /api/workflows/{state,history,start,fire,abort}.
POST bodies must be Content-Type: application/json, and errors answer { error, code } instead of { errors: [{ message, code }] }; the drawer and the widget already use the new endpoints.workflow-instances and workflow-events are refused for everyone, and their reads go through readableWorkflowRuns and readableWorkflowEvents.agents: "deny" refuses them on the endpoints too.req passed to an operation must belong to its user; a request of another user is refused with not-allowed.versions.drafts.localizeStatus), every save that is not a draft save or an unpublish counts as a publish, because Payload publishes the request's locale.Upgrade payload and every @payloadcms/* package to 3.90 or later, run the server on Node 22.22 or later, and install the guard:
pnpm add @focus-reactive/payload-plugin-guard @focus-reactive/payload-plugin-workflows.
Add the plugin's entries to src/access.policy.ts, with gates for your own roles; if the project has no policy file yet, write it first as the guide describes.
// src/access.policy.ts, inside defineAccessPolicy({ ... })
collections: {
"workflow-instances": { create: nobody, read: readableWorkflowRuns, update: nobody, delete: nobody },
"workflow-events": { create: nobody, read: readableWorkflowEvents, update: nobody, delete: nobody },
},
plugins: {
workflows: { view: isAuthor, start: isAuthor, fire: isAuthor, abort: isEditor },
},
view: see workflows: the drawer, the dashboard widget, the state, history and list reads; the user also needs read access to the document.start: start a workflow; the user also needs the right named in documentAccess.start, update by default.fire: take a step, an action of a stage they may act in; the user also needs documentAccess.fire, update by default.abort: stop a workflow; the user also needs documentAccess.abort, update by default.readableWorkflowRuns and readableWorkflowEvents (exported by the plugin) let a user read the runs and events of documents they may read; writes stay nobody.Pass access: accessPolicy.plugins.workflows to workflowsPlugin, and export the config wrapped: export default withAccessPolicy(accessPolicy, buildConfig({ ... })).
Database: the runs collection gains a hidden approved column; on SQL databases without schema push, run payload migrate:create and then payload migrate.
Re-test: an anonymous POST /api/workflows/start answers 401, a user without abort gets 403 from POST /api/workflows/abort, and POST /api/workflow-instances as an admin answers 403; then start a workflow, take each step as its assignee, change the document after approval and check that publishing asks for a new run.
1.0.0 is the first version on npm and already includes every change below; they matter only if you ran a build of the plugin from this repository before it.
Changes to the plugin's collections need a migration on Postgres and SQLite when you do not use schema push (payload migrate:create, then payload migrate):
requiredToPublish (unreleased, before 1.0). Stored shape: the runs collection gains publishedAt and the visibility.fields you configure; the events collection's run is a relationship to the run (run_id, a foreign key, instead of the text column run) and loses actorCollection. API: actors are { id, via } and causes' by is { id } (no collection: every actor is a user of the admin user collection); users of otheTopics
Tags
payload plugin comments
Document-level and field-level comments with mentions, resolution and email notifications for Payload admin
757.0k/wk37v3
payload plugin netlify deploy
Deploy button in the Payload admin that builds a Netlify site, streams the log, and publishes a preview
72370/wk37v3
payload plugin scheduling
Schedule future publication of drafts on collections and globals with a secured cron endpoint
77783/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 audit log
Append-only audit log of document, global and auth changes with CSV and NDJSON export
72394/wk37v3
payload plugin presets
Save and apply reusable block configurations as presets from the Payload admin blocks drawer
786.7k/wk37v3