Workflows

Cookbook: Coordinated release

A release workflow that coordinates approvals across many documents and hands the atomic go-live to a Content Release.

Early access

Coordinate review across every document in a Content Release, then hand the atomic go-live to Sanity. This recipe defines the review child, the parent workflow, and the Functions that call the engine for them.

The release workflow runs in four stages:

  • Assembly: the release groups its documents. The engine starts one review subworkflow for each document. A guard blocks publish on each document until its review is approved; the Content Lake doesn’t enforce it. For what a guard can and can’t enforce, see Guards and enforcement.
  • Scheduled: a release manager schedules the embargoed go-live, or publishes on demand.
  • Published: the release publishes as one unit, and the engine queues the build and notification effects.
  • Archived: the workflow ends here. To roll back, revert the release.

Before you get started

  • Packages: @sanity/workflows, @sanity/client (the release helpers live on client.releases.*), and, for the generated runtime, @sanity/functions and @sanity/blueprints.
  • A Content Release: created up front, with a version document per member (client.releases.create + client.createVersion). This workflow coordinates the review and the timed go-live. It does not create the release. See Content Releases with @sanity/client.
  • An editor token for the content dataset that holds the release. The engine also needs its own client and a workflows dataset to store its instances.
  • A release-manager role in dataset access control (a custom role). The engine offers the schedule action only to this role. That check doesn’t stop writes: dataset access control sets what each token can write.

The recipe uses two workflow definitions. The engine starts one instance of a small review child per document. A parent workflow coordinates the reviews. You pass the release and its documents as global document references, so each one records which project and dataset it lives in.

Define the review child

The review child is a spawn-only (lifecycle: 'child') workflow: one document, one reviewer, approve or request changes.

import {
  defineWorkflow,
  defineField,
  defineStage,
  defineActivity,
  defineAction,
  defineTransition,
  defineGuard,
} from '@sanity/workflows/define'

export const releaseReview = defineWorkflow({
  name: 'release-review',
  title: 'Release document review',
  lifecycle: 'child', // spawn-only: a parent instantiates it, never started cold
  initialStage: 'review',
  fields: [
    defineField({type: 'subject', name: 'subject', initialValue: {type: 'input'}, required: true}),
    defineField({type: 'actor', name: 'reviewer'}),
    defineField({type: 'actor', name: 'approval'}),
    defineField({type: 'string', name: 'changeNote'}),
  ],
  stages: [
    defineStage({
      name: 'review',
      title: 'Review',
      // Per-document publish hold: a guard's `idRefs` resolves to ONE document, so the
      // hold lives here on the child's own `subject`, not on the parent over the whole
      // `documents` array (an array idRef resolves to nothing and deploys no guard).
      // idRefs are typed GuardReads, resolved at deploy and re-synced by the guard refresh.
      guards: [
        defineGuard({
          name: 'hold-publish-review',
          title: 'Hold publish while under review',
          match: {idRefs: [{type: 'fieldRead', field: 'subject'}], actions: ['publish']},
        }),
      ],
      activities: [
        defineActivity({
          name: 'review',
          title: 'Review the document',
          actions: [
            defineAction({
              name: 'claim',
              title: 'Take this review',
              filter: '!defined($fields.reviewer)',
              ops: [{type: 'field.set', target: {field: 'reviewer'}, value: {type: 'actor'}}],
            }),
            defineAction({
              name: 'approve',
              title: 'Approve',
              filter: '$fields.reviewer.id == $actor.id',
              status: 'done',
              ops: [{type: 'field.set', target: {field: 'approval'}, value: {type: 'actor'}}],
            }),
            defineAction({
              name: 'request-changes',
              title: 'Request changes',
              filter: '$fields.reviewer.id == $actor.id',
              status: 'done',
              params: [{type: 'string', name: 'note', title: 'What to change', required: true}],
              ops: [{type: 'field.set', target: {field: 'changeNote'}, value: {type: 'param', param: 'note'}}],
            }),
          ],
        }),
      ],
      transitions: [
        defineTransition({name: 'approved', to: 'approved', when: 'defined($fields.approval)'}),
        defineTransition({name: 'changes', to: 'changes-requested', when: 'defined($fields.changeNote)'}),
      ],
    }),
    defineStage({
      name: 'changes-requested',
      title: 'Changes requested',
      // Still the team's; keep the publish hold until the document is approved.
      guards: [
        defineGuard({
          name: 'hold-publish-changes',
          title: 'Hold publish while changes are pending',
          match: {idRefs: [{type: 'fieldRead', field: 'subject'}], actions: ['publish']},
        }),
      ],
      activities: [
        defineActivity({
          name: 'fix',
          title: 'Address the changes',
          actions: [
            defineAction({
              name: 'resubmit',
              title: 'Resubmit for review',
              status: 'done',
              // clear the note before the move so the review stage's `changes` transition doesn't refire on re-entry
              ops: [{type: 'field.unset', target: {field: 'changeNote'}}],
            }),
          ],
        }),
      ],
      transitions: [
        defineTransition({name: 'back-to-review', to: 'review', when: '$allActivitiesDone'}),
      ],
    }),
    defineStage({name: 'approved', title: 'Approved'}), // terminal: the parent reads this as "cleared for release"
  ],
})

Take review records the caller in the workflow-level reviewer field. The same reviewer keeps the review when the workflow returns to this stage. This actor field does not create a task assignment; use Fields to add one.

Define the release workflow

The parent coordinates the reviews and the timed go-live in one defineWorkflow call:

import {
  defineWorkflow,
  defineField,
  defineStage,
  defineActivity,
  defineAction,
  defineTransition,
} from '@sanity/workflows/define'

export const coordinatedRelease = defineWorkflow({
  name: 'coordinated-release',
  title: 'Coordinated release',
  initialStage: 'assembly',
  fields: [
    defineField({type: 'release.ref', name: 'release', initialValue: {type: 'input'}, required: true}),
    defineField({type: 'doc.refs', name: 'documents', initialValue: {type: 'input'}, required: true}),
    defineField({type: 'datetime', name: 'publishAt'}),
  ],
  stages: [
    defineStage({
      name: 'assembly',
      title: 'Assembly',
      // The publish hold is PER-DOCUMENT, on each release-review child over its single
      // `subject` (see above), NOT a parent guard over the `documents` array. A guard's
      // `idRefs` resolves to one document, so an array target deploys no guard at all.
      activities: [
        defineActivity({
          name: 'reviews',
          title: 'Review every document',
          actions: [
            defineAction({
              name: 'open-reviews',
              when: 'true', // entry trigger: fires on the first cascade after stage entry
              spawn: {
                // GDR rows self-key on their id, so fan out over the doc.refs field directly.
                forEach: '$fields.documents[]',
                definition: {name: 'release-review'},
                with: {subject: '$row'}, // each child reviews one document
              },
            }),
            // Declared after the spawn: triggers run in declaration order, so the entry
            // cascade opens the reviews before this gate first evaluates.
            defineAction({
              name: 'all-reviewed',
              when: "count($subworkflows[activity == 'reviews' && current && status == 'active']) == 0",
              status: 'done',
            }),
          ],
        }),
      ],
      transitions: [defineTransition({name: 'to-scheduled', to: 'scheduled', when: '$allActivitiesDone'})],
    }),
    defineStage({
      name: 'scheduled',
      title: 'Scheduled',
      activities: [
        defineActivity({
          name: 'schedule',
          title: 'Schedule the release',
          actions: [
            defineAction({
              name: 'schedule',
              title: 'Schedule go-live',
              roles: ['release-manager'],
              params: [{type: 'dateTime', name: 'publishAt', title: 'Go-live', required: true}],
              status: 'done',
              ops: [{type: 'field.set', target: {field: 'publishAt'}, value: {type: 'param', param: 'publishAt'}}],
              effects: [
                {name: 'schedule-release', bindings: {release: '$fields.release', publishAt: '$fields.publishAt'}},
              ],
            }),
          ],
        }),
        defineActivity({
          name: 'go-live',
          title: 'Await go-live',
          // off-system: the publish happens in Content Releases, and `target` deep-links
          // the release; a scheduled Function fires `mark-published` once it has published
          target: {type: 'field', field: 'release'},
          actions: [defineAction({name: 'mark-published', title: 'Mark released', status: 'done'})],
        }),
      ],
      transitions: [defineTransition({name: 'to-published', to: 'published', when: '$allActivitiesDone'})],
    }),
    defineStage({
      name: 'published',
      title: 'Published',
      activities: [
        defineActivity({
          name: 'announce',
          title: 'Build and notify',
          actions: [
            defineAction({
              name: 'queue-announcements',
              when: 'true', // entry trigger: queues both effects the moment the stage opens
              effects: [{name: 'build-site'}, {name: 'notify-stakeholders'}],
            }),
            defineAction({
              name: 'confirm-announced',
              when:
                "$effectStatus['build-site'] == 'done' && $effectStatus['notify-stakeholders'] == 'done'",
              status: 'done',
            }),
            defineAction({
              name: 'announcement-failed',
              when:
                "$effectStatus['build-site'] == 'failed' || $effectStatus['notify-stakeholders'] == 'failed'",
              status: 'failed',
            }),
          ],
        }),
      ],
      transitions: [defineTransition({name: 'to-archived', to: 'archived', when: '$allActivitiesDone'})],
    }),
    defineStage({name: 'archived', title: 'Archived'}), // terminal
  ],
})

What each piece does

  • Inputs: release identifies the Content Release; documents lists the members that need review.
  • Review fan-out: open-reviews starts one release-review child per document. all-reviewed completes the parent’s activity once none of the children started in this stage visit is still active.
  • Per-document hold: each child declares the guard on its own subject, because a guard targets one document rather than the parent’s document array. The hold remains until that review is approved.
  • Scheduling: the release manager supplies publishAt. The schedule-release effect schedules the Content Release, and a scheduled Function later confirms publication by firing mark-published.
  • After publication, the engine queues the build and notification effects. Both must succeed before the engine moves the instance to Archived. A failure keeps the instance in Published, where you can see it.

Write the effect handlers

Keep the shared client and each external concern in a small file. Map each effect name in the workflow definition to the handler that performs that work. A handler may receive the same effect more than once, so use the effect key to give repeated calls the same external outcome.

Shared content client

// handlers/content.ts
import {createClient} from '@sanity/client'

export const content = createClient({
  projectId: 'yourprojectid',
  dataset: 'production',
  apiVersion: '2025-02-19',
  token: process.env.SANITY_EDITOR_TOKEN!,
  useCdn: false,
})

Release scheduling

// handlers/schedule-release.ts
import {type EffectHandler, type ReleaseRef} from '@sanity/workflows'
import {content} from './content'

export const scheduleRelease: EffectHandler = async (params) => {
  const release = params.release as ReleaseRef
  const publishAt = params.publishAt as string
  const current = await content.releases.get({releaseId: release.releaseName})

  if (current?.state === 'scheduled' && current.publishAt === publishAt) return

  await content.releases.schedule({
    releaseId: release.releaseName,
    publishAt,
  })
}

Site build

Use the stable effect key as the receiving system’s idempotency key. The deployment hook must honor this header.

// handlers/build-site.ts
import {type EffectHandler} from '@sanity/workflows'

export const buildSite: EffectHandler = async (_params, ctx) => {
  const response = await fetch(process.env.DEPLOY_HOOK_URL!, {
    method: 'POST',
    headers: {'Idempotency-Key': ctx.effectKey},
  })

  if (!response.ok) {
    throw new Error(`Build hook failed: ${response.status}`)
  }
}

Stakeholder notification

Write a deterministic outbox record. A separate worker can deliver the Slack message or email and mark the record complete.

// handlers/notify-stakeholders.ts
import {type EffectHandler} from '@sanity/workflows'
import {content} from './content'

export const notifyStakeholders: EffectHandler = async (_params, ctx) => {
  await content.createIfNotExists({
    _id: `workflow-notification.${ctx.effectKey}`,
    _type: 'workflow.notification',
    instanceId: ctx.instanceId,
    status: 'pending',
  })
}

Map effects to handlers

// handlers/effect-handlers.ts
import {type EffectHandler} from '@sanity/workflows'
import {buildSite} from './build-site'
import {notifyStakeholders} from './notify-stakeholders'
import {scheduleRelease} from './schedule-release'

export const effectHandlers: Record<string, EffectHandler> = {
  'schedule-release': scheduleRelease,
  'build-site': buildSite,
  'notify-stakeholders': notifyStakeholders,
}

Learn more in Content Releases with @sanity/client.

Configure the engine

Create the engine with the workflow dataset client, the effect handlers, and a resourceClients route for the production dataset that holds the release and member documents.

// engine.ts
import {createClient} from '@sanity/client'
import {createEngine, ENGINE_API_VERSION, type ParsedGdr} from '@sanity/workflows'
import {effectHandlers} from './handlers/effect-handlers'
import {content} from './handlers/content'

const workflowClient = createClient({
  projectId: 'yourprojectid',
  dataset: 'workflows',
  apiVersion: ENGINE_API_VERSION,
  token: process.env.SANITY_AUTH_TOKEN,
  useCdn: false,
})

export const engine = createEngine({
  client: workflowClient,
  workflowResource: {type: 'dataset', id: 'yourprojectid.workflows'},
  partition: 'prod',
  effects: {handlers: effectHandlers},
  resourceClients: (parsed: ParsedGdr) =>
    parsed.scheme === 'dataset' && parsed.dataset === 'production' ? content : undefined,
})

Drive it with Functions

Generate the drain and the heartbeat with Generate Functions from your workflow definitions. This recipe adds a Scheduled Function of its own for the Content Release go-live.

Drain queued release effects

In each generated handler stub in effect-handlers/, call this recipe’s handler. The generated drain Function runs whenever the engine queues a new effect on an instance. In each drainEffects() call, the engine runs every scheduling and announcement effect it can claim. Each completed effect lets the engine advance the instance.

A scheduled Function for the go-live

The engine doesn’t act on a timer by itself. A scheduled Function finds releases that are waiting to go live. When Sanity reports a release as published, the Function fires mark-published:

// functions/confirm-go-live/index.ts
import {engine} from '../../engine'
import {content} from '../../handlers/content'

export const handler = async () => {
  const waiting = await engine.query<{_id: string; releaseName: string}[]>({
    groq: `*[_type == "sanity.workflow.instance" && tag == $tag && definition == "coordinated-release" && currentStage == "scheduled" && !defined(completedAt)]{
      _id, "releaseName": fields[name == "release"][0].value.releaseName
    }`,
  })
  for (const wf of waiting) {
    const release = await content.releases.get({releaseId: wf.releaseName})
    if (release?.state === 'published') {
      await engine.fireAction({
        instanceId: wf._id,
        activity: 'go-live',
        action: 'mark-published',
        idempotent: true,
      })
    }
  }
}

engine.query binds the engine's partition as $tag, and the stored instance field is named tag, so the query filters on tag == $tag. A query can miss a commit made in the last second or so; see commit visibility.

The generated heartbeat Function ticks workflow instances. It also re-evaluates parents that missed a child finishing. It doesn’t check releases, so deploy the go-live check as its own scheduled Function.

Deploy it

First, deploy both workflow definitions: the parent and its child. The parent can only spawn the child after the child is deployed. The CLI reads the definitions from sanity.workflow.ts:

A reader model is the lowest stored-data model version an engine must support to read a definition. The coordinatedRelease definition reads $effectStatus, which needs reader model 13. The required content-reference fields in both definitions alone would need 10. Before you deploy, follow the package rollout order and check that every runtime sharing the workflow resource can read model 13. Then the config sets expectedMinReaderModel: 13 to confirm it, because both definitions deploy together.

// sanity.workflow.ts
import {defineWorkflowConfig} from '@sanity/workflows/define'
import {coordinatedRelease} from './coordinated-release'
import {releaseReview} from './release-review'

export default defineWorkflowConfig({
  deployments: [
    {
      name: 'production',
      partition: 'prod',
      expectedMinReaderModel: 13,
      workflowResource: {type: 'dataset', id: 'yourprojectid.workflows'},
      definitions: [releaseReview, coordinatedRelease],
    },
  ],
})

Then log in and deploy the definitions:

npx sanity@latest login
npx sanity-workflows deploy

Deploying a changed definition creates a new version. See Configure and deploy workflow definitions for sharing and deployment options.

Deploy confirm-go-live separately from the generated Functions:

  • Scheduled Functions deploy only to an organization-scoped stack.
  • The generator rewrites the heartbeat stack each time it runs, so don’t add your Function there.
  • Give confirm-go-live its own blueprint, its own organization-scoped stack, and its own robot token. The generated heartbeat stack uses the same setup.

Deploy that stack with an organization deploy token. Replace <organizationId> with your organization ID:

# from the directory that holds the confirm-go-live blueprint
npx sanity@latest blueprints init . --organization-id <organizationId> # first deploy only
npx sanity@latest blueprints deploy

The generated drain Function calls the engine to run the release effects. The confirm-go-live Function confirms publication.

Run it

Start an instance with the release and its member documents:

import {refDataset, releaseRef} from '@sanity/workflows'
import {engine} from './engine'

const release = releaseRef({res: {type: 'dataset', id: 'yourprojectid.production'}, releaseName: 'spring-launch'})

// verbs return an OperationResult; the instance document is on .instance
const {instance: wf} = await engine.startInstance({
  definition: 'coordinated-release',
  initialFields: [
    {type: 'release.ref', name: 'release', value: release},
    {
      type: 'doc.refs',
      name: 'documents',
      value: [
        refDataset({projectId: 'yourprojectid', dataset: 'production', documentId: 'landing', type: 'page'}),
        refDataset({projectId: 'yourprojectid', dataset: 'production', documentId: 'pricing', type: 'page'}),
        refDataset({projectId: 'yourprojectid', dataset: 'production', documentId: 'launch-post', type: 'article'}),
      ],
    },
  ],
})

// One release-review child spawns per document; reviewers claim and approve each
// (see the Editorial review example for the per-review calls). Once every child
// is approved, the workflow moves to 'scheduled'. Then a release manager:
await engine.fireAction({
  instanceId: wf._id,
  activity: 'schedule',
  action: 'schedule',
  params: {publishAt: '2026-07-01T09:00:00Z'},
})

// A scheduled Function then confirms the go-live: once Sanity publishes the release
// it fires `mark-published`, advancing the workflow to 'published'.

The engine spawns one review child per document. Once every child is approved, the engine moves the instance to Scheduled. At go-live the release publishes as one unit. The engine then queues the build and notification effects; both must succeed before it moves the instance to Archived.

This diagram shows who does what. A manager starts the release workflow and schedules the go-live. Reviewers approve each child workflow through engine actions. Functions call the engine to run the schedule effect, and confirm publication. The engine moves the workflow from Assembly to Scheduled, Published, and Archived. The Content Lake stores each state.

Adapting it

  • Publish on demand instead of scheduling: drop the publishAt param and have the effect call client.releases.publish immediately.
  • Reuse the editorial example: if each document is written fresh for the launch, use it as the child rather than the review-only child here.
  • Predicated guards: the holds here are unconditional denies. Give a guard a predicate (GROQ over the mutation) to allow specific writes while the hold stands, for example permitting metadata patches on a member document while still denying publish.
  • Cardinality: a single-document release is the same machine with one child. Sanity’s Scheduled Drafts are exactly that.

Next steps

Visiting agent?

Was this page helpful?

Sanity logosanity.ioAll Systems Operational© Sanity 2026
Change site theme