Build a workflow interface with the App SDK
Render live workflow state and commit actions from your own App SDK application: mount a session, handle its states, render activities and fields from the evaluation, and list instances.
Early access
Workflows is in early access, built in public. Read How early access works before you rely on it.
This page is for applications outside Studio. To build a Document Action, tool, pane, input, or dialog inside Studio, see Create a workflow-powered Document Action. Choose an integration compares the packages.
When the Studio plugin does not fit the interface you need, use @sanity/workflow-sdk to build the workflow experience in an App SDK application. It supplies live workflow state and the engine operations that change it.
This guide builds one App SDK screen: a workflow panel that shows an instance’s stage, fires its actions, and edits a field, then an instance list that opens the panel. For assignment, actor, and date controls, see Reusable UI components. For the underlying live-data model, see The reactive session.
You need:
- The Workflows quick start completed. This guide uses its
article-reviewdefinition and thedevdeployment insanity.workflow.ts. - An App SDK app for the same Sanity project. To create one, follow the App SDK quick start.
- Familiarity with editable workflow fields and transition conditions. The next section adds both to the quick start definition.
Install the runtime
Use @sanity/sdk and @sanity/sdk-react 3.1 or later in the 3.x line. Install matching SDK versions and one matching version for every @sanity/workflow-* package. Use Workflows 0.37.0 or later, the version the quick start installs. Earlier versions name the partition tag and reject the partition setting this guide uses.
SDK 3.1.0 can resolve @sanity/mutate 0.18.1, which can leave document reads pending with Sanity client 8. Before installing, merge this override into your application’s root package-manager configuration:
{
"overrides": {
"@sanity/sdk": {
"@sanity/mutate": "0.18.2"
}
}
}overrides:
'@sanity/sdk@3>@sanity/mutate': 0.18.2Install the App SDK adapter, shared controls, and their host dependencies:
npm install @sanity/sdk@^3.1 @sanity/sdk-react@^3.1 \
@sanity/ui@^4.2.1 react@^19.2.7 react-dom@^19.2.7 \
styled-components@^6.4.2 @sanity/workflow-components \
@sanity/workflow-engine @sanity/workflow-react @sanity/workflow-sdkpnpm add @sanity/sdk@^3.1 @sanity/sdk-react@^3.1 \
@sanity/ui@^4.2.1 react@^19.2.7 react-dom@^19.2.7 \
styled-components@^6.4.2 @sanity/workflow-components \
@sanity/workflow-engine @sanity/workflow-react @sanity/workflow-sdkyarn add @sanity/sdk@^3.1 @sanity/sdk-react@^3.1 \
@sanity/ui@^4.2.1 react@^19.2.7 react-dom@^19.2.7 \
styled-components@^6.4.2 @sanity/workflow-components \
@sanity/workflow-engine @sanity/workflow-react @sanity/workflow-sdkbun add @sanity/sdk@^3.1 @sanity/sdk-react@^3.1 \
@sanity/ui@^4.2.1 react@^19.2.7 react-dom@^19.2.7 \
styled-components@^6.4.2 @sanity/workflow-components \
@sanity/workflow-engine @sanity/workflow-react @sanity/workflow-sdk@sanity/workflow-react supplies the shared reactive hooks used in this guide. The UI examples use Sanity UI 4 and must render inside its theme provider.
Run npm ls @sanity/sdk @sanity/mutate or pnpm why @sanity/mutate. Confirm that SDK 3 resolves Mutate 0.18.2; other dependency branches may use different versions. Commit the configuration and updated lockfile.
Keep the override until your SDK release requires Mutate 0.18.2 or later and excludes 0.18.1. After removing it, reinstall and verify the dependency tree again.
Prepare the workflow
The panel in this guide edits a score, and the transition out of review waits on that score and a legal approval. The quick start definition has no field the panel can edit and no condition to wait on. In workflows/article-review.ts, add two editable fields and a when condition on to-approved:
export const articleReview = defineWorkflow({
// ...
fields: [
defineField({
type: 'subject',
name: 'subject',
// ...
}),
defineField({type: 'number', name: 'score', title: 'Score', editable: true}),
defineField({type: 'boolean', name: 'legalApproved', title: 'Legal approved', editable: true}),
],
stages: [
// drafting is unchanged
defineStage({
name: 'review',
// ...
transitions: [
defineTransition({
name: 'to-approved',
title: 'Approve and finish',
to: 'approved',
when: '$allActivitiesDone && $fields.legalApproved == true && $fields.score > 5',
}),
],
}),
// approved is unchanged
],
})editable: true lets a user change the field while the instance runs. Without it, the field is not in the evaluation’s editableFields. The when condition keeps the instance in review after sign-off resolves, until the score is above 5 and legal approval is set.
Redeploy the definition:
npx sanity-workflows deploypnpm dlx sanity-workflows deployyarn dlx sanity-workflows deploybunx sanity-workflows deployThe quick start instance is already in approved, and it stays pinned to the version it started under. Start a new instance against the same article:
npx sanity-workflows start article-review \
--field subject='{"id":"dataset:PROJECT_ID:DATASET_NAME:DOCUMENT_ID","type":"article"}'pnpm dlx sanity-workflows start article-review \
--field subject='{"id":"dataset:PROJECT_ID:DATASET_NAME:DOCUMENT_ID","type":"article"}'yarn dlx sanity-workflows start article-review \
--field subject='{"id":"dataset:PROJECT_ID:DATASET_NAME:DOCUMENT_ID","type":"article"}'bunx sanity-workflows start article-review \
--field subject='{"id":"dataset:PROJECT_ID:DATASET_NAME:DOCUMENT_ID","type":"article"}'Started dev.wf-instance.a1b2c3d4e5f6 — now at draftingKeep the id. The examples below use it as INSTANCE_ID.
Create a live session
A session loads the instance, evaluates its definition against the content it references, and re-evaluates when that content, its guards, or a field preview changes. The reactive session explains the model.
Create one workflow session for the instance currently open in a detail view. The session keeps that instance's evaluation current and provides the operations that change it. Pass the engine and instance ID to useWorkflowSession. Build the engine with useWorkflowEngine, using the dataset and partition: 'dev' from the quick start’s dev deployment. An engine on another partition cannot see the instance. Use the hooks in List instances and open one to let the user choose an instance without creating a session for every row.
Do not edit workflow instances as content
Do not use useEditDocument or other content-editing APIs to change workflow instance documents. They bypass engine transactions and can break the audit trail or leave the instance internally inconsistent. Use the session’s operations instead. See Instance writes are transactions.
import {useWorkflowEngine, useWorkflowSession} from '@sanity/workflow-sdk'
export function WorkflowPanel({instanceId}: {instanceId: string}) {
// The same dataset and partition as the dev deployment in sanity.workflow.ts.
const engine = useWorkflowEngine({
workflowResource: {type: 'dataset', id: 'PROJECT_ID.DATASET_NAME'},
partition: 'dev',
})
const session = useWorkflowSession({engine, instanceId})
// A real UI also handles session.invalid, session.error, and
// session.evaluationError before treating a missing evaluation as loading.
if (!session.ready || !session.evaluation) return <p>Loading…</p>
return <pre>{session.evaluation.instance.currentStage}</pre>
}Mount it inside SanityApp, configured for the dataset your content lives in. The UI examples need the Sanity UI theme provider, and WorkflowTelemetryProvider lets the engine report its telemetry. Replace INSTANCE_ID with the id the start command printed:
import {SanityApp} from '@sanity/sdk-react'
import {ThemeProvider} from '@sanity/ui'
import {buildTheme} from '@sanity/ui/theme'
import {WorkflowTelemetryProvider} from '@sanity/workflow-sdk'
import {WorkflowPanel} from './WorkflowPanel'
const theme = buildTheme()
export function App() {
return (
<SanityApp
config={[{projectId: 'PROJECT_ID', dataset: 'DATASET_NAME'}]}
fallback={<p>Loading…</p>}
>
<ThemeProvider theme={theme}>
<WorkflowTelemetryProvider>
<WorkflowPanel instanceId="INSTANCE_ID" />
</WorkflowTelemetryProvider>
</ThemeProvider>
</SanityApp>
)
}The App SDK client token identifies the actor and authorizes the session’s commits.
Render the workflow
A workflow screen must distinguish “still loading” from “this instance cannot be read.” The session reports that state and exposes the evaluation, a read-only projection of the workflow for the current actor, plus the operations that commit changes.
Handle invalid, error, and evaluationError before loading. Render the workflow only when ready is true and an evaluation is available. The complete WorkflowPanel handles them in that order. Session states explains what each state means.
A failed evaluation retains the last successful evaluation. Check evaluationError before displaying that value as current. Loading content is unresolved; it is not evidence that a referenced document was deleted.
Render activities and actions
The authored definition says which actions could exist. It does not tell your UI what is available right now. Map evaluation.currentStage.activities, then pass each entry from activity.actions to the action control. The evaluation classifies each action as filtered out, automated, allowed, or blocked:
import {Button, Text} from '@sanity/ui'
import {actionRendering, type ActionEvaluation} from '@sanity/workflow-engine'
import type {WorkflowSession} from '@sanity/workflow-sdk'
export function ActionButton({
action,
activity,
fire,
}: {
action: ActionEvaluation
activity: string
fire: WorkflowSession['fireAction']
}) {
const rendering = actionRendering(action)
const title = action.action.title ?? action.action.name
if (rendering === 'absent') return null
if (rendering === 'automation') return <Text muted>{title} runs automatically</Text>
return (
<Button
disabled={!action.allowed}
mode="ghost"
onClick={() => void fire({activity, action: action.action.name})}
text={title}
/>
)
}Render editable fields
Editing every keystroke as a workflow commit would create a separate history entry for every change. The evaluation’s editableFields identify what the current actor may edit. Use previewField for immediate feedback, then editField when the user deliberately commits:
import {useState} from 'react'
import type {WorkflowSession} from '@sanity/workflow-sdk'
export function ScoreField({session}: {session: WorkflowSession}) {
const [draft, setDraft] = useState<number>()
const field = session.evaluation?.editableFields.find((entry) => entry.name === 'score')
if (field === undefined) return null
return (
<input
type="number"
value={draft ?? Number(field.value ?? 0)}
disabled={!field.editable}
onChange={(event) => {
const value = Number(event.target.value)
setDraft(value)
session.previewField({field, value})
}}
onBlur={(event) => {
setDraft(undefined)
void session.editField({field, value: Number(event.target.value)})
}}
/>
)
}Check the panel
Render the actions and the score field in WorkflowPanel, and handle each session state before the loading check. This is the complete component:
import {Spinner, Stack, Text} from '@sanity/ui'
import {errorMessage} from '@sanity/workflow-engine'
import {useWorkflowEngine, useWorkflowSession} from '@sanity/workflow-sdk'
import {ActionButton} from './ActionButton'
import {ScoreField} from './ScoreField'
export function WorkflowPanel({instanceId}: {instanceId: string}) {
const engine = useWorkflowEngine({
workflowResource: {type: 'dataset', id: 'PROJECT_ID.DATASET_NAME'},
partition: 'dev',
})
const session = useWorkflowSession({engine, instanceId})
if (session.invalid) return <Text>Unreadable instance: {session.invalid.message}</Text>
if (session.error) return <Text>Could not load workflow: {errorMessage(session.error)}</Text>
if (session.evaluationError) {
return <Text>Could not evaluate workflow: {errorMessage(session.evaluationError)}</Text>
}
if (!session.ready || !session.evaluation) return <Spinner />
const {currentStage, instance} = session.evaluation
return (
<Stack gap={3}>
<Text weight="semibold">{instance.currentStage}</Text>
{currentStage.activities.flatMap(({activity, actions}) =>
actions.map((action) => (
<ActionButton
action={action}
activity={activity.name}
fire={session.fireAction}
key={`${activity.name}/${action.action.name}`}
/>
)),
)}
<ScoreField session={session} />
</Stack>
)
}Run the app. The panel shows drafting and a Submit for review button. Select it. The panel switches to review and shows Approve. Confirm the change from a terminal:
npx sanity-workflows show INSTANCE_IDpnpm dlx sanity-workflows show INSTANCE_IDyarn dlx sanity-workflows show INSTANCE_IDbunx sanity-workflows show INSTANCE_IDThe Stage row reads review. If you select Approve now, the instance stays in review: the when condition still waits on the score and legal approval. To tell the user what remains, see Explain workflow decisions.
List instances and open one
A session covers one instance. To let the user choose which instance to open, list instances with useWorkflowInstances and mount WorkflowPanel for the selected one:
import {Button, Stack, Text} from '@sanity/ui'
import {errorMessage} from '@sanity/workflow-engine'
import {useWorkflowEngine, useWorkflowInstances} from '@sanity/workflow-sdk'
import {useState} from 'react'
import {WorkflowPanel} from './WorkflowPanel'
export function WorkflowsTool() {
const [selectedId, setSelectedId] = useState<string>()
if (selectedId) {
return (
<Stack gap={3}>
<Button mode="bleed" onClick={() => setSelectedId(undefined)} text="Back to workflows" />
<WorkflowPanel instanceId={selectedId} />
</Stack>
)
}
return <WorkflowList onSelect={setSelectedId} />
}
function WorkflowList({onSelect}: {onSelect: (instanceId: string) => void}) {
const engine = useWorkflowEngine({
workflowResource: {type: 'dataset', id: 'PROJECT_ID.DATASET_NAME'},
partition: 'dev',
})
const {instances, loading, unreadable, error} = useWorkflowInstances({engine})
if (error) return <Text>Could not load workflows: {errorMessage(error)}</Text>
if (loading) return <Text muted>Loading workflows…</Text>
return (
<Stack gap={3}>
{unreadable.length > 0 ? (
<Text muted>{unreadable.length} workflow document(s) could not be read.</Text>
) : null}
{instances?.length ? (
instances.map((instance) => (
<Button
key={instance._id}
mode="ghost"
onClick={() => onSelect(instance._id)}
text={`${instance.definition}: ${instance.currentStage}`}
/>
))
) : (
<Text muted>No workflow instances in progress.</Text>
)}
</Stack>
)
}The list handles a read error, loading, unreadable workflow documents, and an empty result before it renders rows. Without a filter, useWorkflowInstances returns in-flight instances only, so the finished quick start instance does not appear.
In src/App.tsx, import WorkflowsTool from ./WorkflowsTool and render <WorkflowsTool /> in place of <WorkflowPanel instanceId="INSTANCE_ID" />.
Run the app. The list shows article-review: review for the instance you started. Select it to open the panel, and select Back to workflows to return to the list.
To show the workflows for one document, or a dashboard over many instances, see Instance list hooks.
Next steps
- The reactive session for the conceptual model this page renders.
- Reusable UI components: resolve actor names, edit assignments with the shared pickers, and choose an instance list hook.
- Evaluation insights: explain why an action is blocked or a transition is still waiting.
- Test a workflow before you deploy it: the test bench evaluates the same projection, so helpers like the ones on this page are directly assertable.
- Reference guide for the full API surface.
- Build a custom reactive adapter: integrate another host or data layer.
Visiting agent?
Workflows includes an MCP server for inspecting, operating, authoring, validating, and deploying workflows. Ask your human to set up the MCP server.
Was this page helpful?
Feedback submitted, thanks for helping us improve the docs. Have you tried these alternatives?