Run Workflows with Sanity Functions
Use GROQ-triggered and scheduled Sanity Functions to start workflows, reevaluate conditions, and process queued effects.
Early access
Workflows is in early access, built in public. Read How early access works before you rely on it.
Use Sanity Functions to call the Workflows engine without maintaining a server.
A Document Function responds to GROQ-filtered document changes. A Scheduled Function reevaluates workflows as time passes. An effect is external work queued by a workflow. A Function with the required handlers runs it.
This guide configures the Functions yourself. To generate them from your workflow definitions instead, follow the experimental guide Generate Functions from your workflow definitions.
You need:
- The finished quick start:
article-reviewdeployed, and asanity.workflow.tsthat exports thedevdeployment. - Run the engine from your own code. The Functions in this guide build their own client and engine the same way, against the same dataset and
partition: 'dev'. - Handle asynchronous work with effects: an effect declared on
article-review, redeployed, and theeffect-handlers.tsmodule that guide creates at the project root, which exportseffectHandlers. Without an effect, the drainer has nothing to run. - Write GROQ conditions: a transition or action whose
whenreads$now. Without a time-based condition,tick()on a schedule changes nothing. - Familiarity with Sanity Functions and Blueprints, and an organization-scoped stack on a plan that allows the cron schedule you choose.
This guide deploys two Functions: a Document Function that drains queued effects as soon as work appears, and a Scheduled Function that calls tick() on in-flight instances so time-based conditions are reevaluated. For other pairings of a trigger and an engine operation, such as starting an instance when content becomes eligible, see Choose a Function for each use case.
Keep document triggers narrow
Engine operations mutate workflow instance documents when they claim work, record outcomes, append history, or move between stages. A Document Function can therefore react to mutations produced by its own previous call.
Filter for the smallest document delta that makes the engine operation useful. Broad filters spend invocations and reads on no-op calls. They can also keep waking the same Function as its previous invocation updates the instance.
For an effect drainer, run only when the number of unclaimed pending effects increases:
_type == "sanity.workflow.instance" &&
tag == "dev" &&
count(after().pendingEffects[!defined(claim)]) >
coalesce(count(before().pendingEffects[!defined(claim)]), 0)The comparison between after() and before() detects newly available work. Claiming or completing an existing effect does not increase the count, so those mutations do not wake the Function again.
The coalesce(..., 0) fallback also handles a newly created instance that already contains pending work. A filter that only checks whether pending work exists is simpler, but unrelated instance mutations can then cause repeated invocations while the work remains.
Install the Functions packages
Install the Functions runtime and the Blueprints definitions in the quick start project. @sanity/client is already installed from the engine guide:
npm install @sanity/functions
npm install --save-dev @sanity/blueprintspnpm add @sanity/functions
pnpm add --save-dev @sanity/blueprintsyarn add @sanity/functions
yarn add --dev @sanity/blueprintsbun add @sanity/functions
bun add --dev @sanity/blueprintsDeploy the Blueprint
The Blueprint below binds the effect drainer to its GROQ event and the Scheduled Function to its cron schedule. Both Functions use the same robot token. Scheduled Functions are organization-scoped and do not receive a target project or dataset in event context, so the Blueprint passes those values as environment variables. Follow Define a robot token with Blueprints for the token resource and membership fields.
import {
defineBlueprint,
defineDocumentFunction,
defineRobotToken,
defineScheduledFunction,
} from '@sanity/blueprints'
// The project and dataset from the dev deployment's workflowResource
const projectId = 'PROJECT_ID'
const dataset = 'DATASET_NAME'
const robotToken = '$.resources.wf-dev-runtime.token'
export default defineBlueprint({
resources: [
defineRobotToken({
name: 'wf-dev-runtime',
label: 'Workflows runtime',
memberships: [
{resourceType: 'project', resourceId: projectId, roleNames: ['editor']},
],
}),
defineDocumentFunction({
name: 'wf-dev-drain-effects',
src: './functions/wf-dev-drain-effects',
project: projectId,
robotToken,
event: {
on: ['create', 'update'],
filter:
'_type == "sanity.workflow.instance" && tag == "dev" && ' +
'count(after().pendingEffects[!defined(claim)]) > ' +
'coalesce(count(before().pendingEffects[!defined(claim)]), 0)',
projection: '{_id}',
resource: {type: 'dataset', id: `${projectId}.${dataset}`},
},
}),
defineScheduledFunction({
name: 'wf-dev-tick-instances',
src: './functions/wf-dev-tick-instances',
event: {expression: '* * * * *'},
robotToken,
env: {
SANITY_PROJECT_ID: projectId,
SANITY_DATASET: dataset,
},
}),
],
})Replace PROJECT_ID and DATASET_NAME with the values from the dev deployment’s workflowResource, so the Functions use the quick start dataset. Keep the partition identical in the drainer trigger, engine configuration, and Scheduled Function query. Engine APIs take it as partition; the stored instance field keeps the name tag, so the GROQ filter reads tag == "dev". Set the cron expression to the maximum delay your time-based workflow decisions can tolerate and that your plan supports.
Drain effects when work is queued
A Function runs outside your project, so it can’t import scripts/engine.ts. Each handler builds its own client and engine from the Function context, with partition: 'dev'. The effectHandlers object comes from the effects guide and maps each effect name to the code that performs it. When unclaimed work appears, the Function calls drainEffects() once for the instance in the event.
import {createClient} from '@sanity/client'
import {documentEventHandler} from '@sanity/functions'
import {createEngine, ENGINE_API_VERSION} from '@sanity/workflow-engine'
import {effectHandlers} from '../../effect-handlers'
interface WorkflowEvent {
_id: string
}
export const handler = documentEventHandler<WorkflowEvent>(
async ({context, event}) => {
const projectId = context.clientOptions.projectId
const dataset = context.clientOptions.dataset
if (!projectId || !dataset) {
throw new Error('The Function event has no project or dataset')
}
const client = createClient({
...context.clientOptions,
projectId,
dataset,
apiVersion: ENGINE_API_VERSION,
perspective: 'raw',
useCdn: false,
})
const engine = createEngine({
client,
workflowResource: {type: 'dataset', id: `${projectId}.${dataset}`},
partition: 'dev',
executionContext: {kind: 'drainer', id: 'wf-dev-drain-effects'},
effects: {
handlers: effectHandlers,
// Leave other effects pending for the drainer that owns them.
missingHandler: 'skip',
},
})
await engine.drainEffects({instanceId: event.data._id})
},
)One drainEffects() call continues until no effect registered by this Function can be claimed. After each handler completes, the engine reevaluates automatic transitions. Effects queued during that reevaluation are available to the same drain.
Do not add an outer loop or call tick() after the drain. Those calls repeat reads and cascade evaluation without advancing the effect queue.
A drain may run several handlers, so budget for their combined duration. A handler may receive the same effect more than once. Use ctx.effectKey as the idempotency key for any external write. Use separate drainers before their combined work approaches the Function timeout.
Tick workflows on a schedule
This Scheduled Function selects in-flight instances and completed instances that still have pending effects. It releases expired claims on both. It calls tick() only for in-flight instances, running automatic progression until each is stable.
sweepStaleClaims() releases ownership left by a handler that stopped before recording an outcome. Releasing a claim increases the unclaimed-work count and wakes the effect drainer. Completed instances need this recovery too: reaching a terminal stage does not discard queued effects.
import {createClient} from '@sanity/client'
import {scheduledEventHandler} from '@sanity/functions'
import {
createEngine,
ENGINE_API_VERSION,
errorMessage,
instancesQuery,
sweepStaleClaims,
} from '@sanity/workflow-engine'
export const handler = scheduledEventHandler(async ({context}) => {
const projectId = process.env.SANITY_PROJECT_ID
const dataset = process.env.SANITY_DATASET
if (!projectId || !dataset) {
throw new Error('The Scheduled Function requires SANITY_PROJECT_ID and SANITY_DATASET')
}
const client = createClient({
...context.clientOptions,
projectId,
dataset,
apiVersion: ENGINE_API_VERSION,
perspective: 'raw',
useCdn: false,
})
const executionContext = {kind: 'server', id: 'wf-dev-tick-instances'} as const
const engine = createEngine({
client,
workflowResource: {type: 'dataset', id: `${projectId}.${dataset}`},
partition: 'dev',
executionContext,
})
const {query, params} = instancesQuery({
partition: 'dev',
filter: {includeCompleted: true},
})
const instances = await client.fetch<Array<{_id: string; completedAt: string | null}>>(
`${query}[!defined(completedAt) || count(pendingEffects) > 0]{_id, completedAt}`,
params,
)
let failed = 0
for (const {_id, completedAt} of instances) {
try {
await sweepStaleClaims({
client,
partition: 'dev',
instanceId: _id,
executionContext,
})
if (completedAt === null) {
await engine.tick({instanceId: _id})
}
} catch (error) {
failed += 1
console.error(`Scheduled recovery failed for ${_id}: ${errorMessage(error)}`)
}
}
if (instances.length > 0 && failed === instances.length) {
throw new Error('Scheduled recovery failed for every selected instance')
}
})tick() does not run effect handlers. If this Scheduled Function also owns the handlers, register them on its engine. Call drainEffects() for every selected instance after the sweep and optional tick, including completed instances. This runs queued effects in the same invocation, but checks for effects on every schedule.
Handle each instance independently so one failure does not stop recovery for the others. Fail the invocation when every selected instance fails so the problem remains visible in logs.
Time passing does not advance an instance until something calls tick(). A tick() result can include nextEvaluationAt, the earliest future time the engine can derive for a time-based change to the instance. It is absent on a finished instance and whenever the engine cannot derive a boundary, so a missing value does not mean an active instance has nothing left to wait for.
Time-based conditions must read $now, or dateTime($now) for datetime comparisons. Definition validation rejects now() and dateTime::now().
Outside Functions, a long-running worker can schedule its own ticks. This function takes a configured engine, such as the engine that scripts/engine.ts exports, and an existing instance ID. It waits until nextEvaluationAt or one minute, whichever comes first:
import type {Engine} from '@sanity/workflow-engine'
export async function tickOnSchedule(engine: Engine, instanceId: string) {
while (true) {
const result = await engine.tick({instanceId})
if (result.instance.completedAt) return
const untilNext = result.nextEvaluationAt
? Date.parse(result.nextEvaluationAt) - Date.now()
: 60_000
const delay = Math.max(1, Math.min(untilNext, 60_000))
await new Promise<void>((resolve) => setTimeout(resolve, delay))
}
}Call await tickOnSchedule(engine, instanceId) from a long-running worker. It stops when the instance completes or is canceled. A failed tick rejects the call; your worker must handle the failure.
The one-minute fallback also picks up data changes and time conditions with no reported boundary. The timer lasts only while the process runs, so hosted workflows use the Scheduled Function in this section instead.
Test and deploy
- Use Testing functions locally to exercise both handlers with representative payloads and credentials. Invoke each effect handler more than once with the same
ctx.effectKeyand confirm that it does not repeat the external write. - Deploy to a non-production stack and verify that the document trigger detects new work with GROQ
before()andafter(). Local Function test commands cannot evaluate these delta functions. See GROQ feature support across Sanity. - Confirm that new work invokes the drainer, claim and completion mutations do not create an invocation loop, and interrupted handlers' expired claims become available again. Include a completed instance with pending effects in the recovery test. A scheduled tick that changes no state must not write.
npx sanity blueprints deploypnpm dlx sanity blueprints deployyarn dlx sanity blueprints deploybunx sanity blueprints deployUse the Functions cheat sheet for deployment and log commands.
Check the result
The quick start instance is already finished, so start a new one and fire submit. Entering review fires the notify trigger from the effects guide, which queues notify-reviewer:
npx sanity-workflows start article-review \
--field subject='{"id":"dataset:PROJECT_ID:DATASET_NAME:DOCUMENT_ID","type":"article"}'
npx sanity-workflows fire-action INSTANCE_ID --activity write --action submitpnpm dlx sanity-workflows start article-review \
--field subject='{"id":"dataset:PROJECT_ID:DATASET_NAME:DOCUMENT_ID","type":"article"}'
pnpm dlx sanity-workflows fire-action INSTANCE_ID --activity write --action submityarn dlx sanity-workflows start article-review \
--field subject='{"id":"dataset:PROJECT_ID:DATASET_NAME:DOCUMENT_ID","type":"article"}'
yarn dlx sanity-workflows fire-action INSTANCE_ID --activity write --action submitbunx sanity-workflows start article-review \
--field subject='{"id":"dataset:PROJECT_ID:DATASET_NAME:DOCUMENT_ID","type":"article"}'
bunx sanity-workflows fire-action INSTANCE_ID --activity write --action submitThe command returns as soon as the effect is queued, and the new pending work invokes the drainer. Give it a moment, then show the instance with its history:
npx sanity-workflows show INSTANCE_ID --include historypnpm dlx sanity-workflows show INSTANCE_ID --include historyyarn dlx sanity-workflows show INSTANCE_ID --include historybunx sanity-workflows show INSTANCE_ID --include historyThe Pending effects section is gone, and the History section includes Effect settled: notify-reviewer (done). If the effect is still listed under Pending effects, check the drainer’s logs.
To check the Scheduled Function, run show again after your $now condition becomes true. Within one cron interval, Stage reports the stage the time-based transition moves to.
Was this page helpful?
Feedback submitted, thanks for helping us improve the docs. Have you tried these alternatives?