Workflows

Write GROQ conditions

Write GROQ conditions for workflow start filters, requirements, stage transitions, and activity gates.

Early access

Conditions are GROQ expressions that answer a yes-or-no question about workflow state. Where you declare one decides what it controls: a transition’s when moves the instance, an action’s when fires it, a filter decides whether an activity or action exists, and requirements decide whether it can run.

This guide writes conditions on the quick start’s article-review workflow: a transition that waits for legal sign-off, a named predicate that reuses it, start rules that decide when a review can begin, and a route for articles that come back for a second review. Each step ends with a CLI check.

Prerequisites

  • The finished quick start: workflows/article-review.ts deployed through the dev deployment in sanity.workflow.ts, and the _id of the published article you started it with.
  • Basic GROQ: filters, defined(), and count().
  • For the first check: scripts/approve-legal.ts from Configure workflow fields, which sets a field through the engine.

Know what a condition can read

The engine evaluates each condition against a small snapshot it builds for that decision, not against the whole Content Lake. The snapshot holds the current instance, its ancestor instances, and its live child instances; the readable documents named by subject, doc.ref, and doc.refs fields at workflow or current-stage scope; and the release named by a release.ref field.

Missing or unreadable documents are absent from the snapshot, and the engine does not follow references beyond that first hop. A single reference field resolves to the full document in $fields, so $fields.subject.title works; when its document is absent, the value has only _id and _type. Other fields render as their stored values, and doc.refs stays an array of reference identities. Variables such as $fields, $stage, $allActivitiesDone, and $self are available depending on the site; Condition variables and decision sites lists which variables each site binds.

Only an action filter, an activity’s requirements, and an editable condition can read the caller ($actor, $assigned, $can, $attributes). Routing conditions give the same answer whoever drives the call, so defineWorkflow and deploy reject a transition when that reads $assigned. Actors and enforcement explains why, and Let reviewers claim an assignment shows a caller-bound filter in use.

Use $now for the evaluation time. It is an ISO-8601 string, so compare with dateTime($now). Validation rejects now() and dateTime::now() in conditions, predicates, spawn expressions, start.filter, and GROQ start requirements, because the runtime must know which expressions need re-evaluating as time passes. Query initial values on fields are the exception; see Configure workflow fields.

A condition that GROQ cannot decide returns null, and null stops transition selection instead of falling through to the next transition. Selection, cascade, and settling explains the rule. Guard optional values with defined() or coalesce().

Wait for a field in a transition

Add an editable legalApproved field and make to-approved wait for it as well as for sign-off:

export const articleReview = defineWorkflow({
  // ...
  fields: [
    defineField({
      type: 'subject',
      name: 'subject',
      // ...
    }),
    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',
        }),
      ],
    }),
    // approved is unchanged
  ],
})

A transition without when waits for $allActivitiesDone. This when keeps that check and adds the field, so an instance stays in review after sign-off until someone sets legalApproved to true. Deploy, start a new instance, and fire write/submit and sign-off/approve as in the quick start.

Run npx sanity-workflows show INSTANCE_ID. The instance is still in review, and show reports STUCK — no exit transition's trigger is satisfied because every activity is done. Set the field with the scripts/approve-legal.ts script from Configure workflow fields and the instance moves to approved in the same call. To see why a condition is waiting from code, read its insight; Explain waiting conditions shows how.

Reuse a rule with a named predicate

When several decisions use the same instance rule, declare it once in predicates and reference it as $name. A named predicate can read instance variables, but not caller variables or another named predicate. The name attributes is reserved for $attributes.

export const articleReview = defineWorkflow({
  // ...
  predicates: {
    readyToApprove: '$allActivitiesDone && $fields.legalApproved == true',
  },
  stages: [
    // drafting is unchanged
    defineStage({
      name: 'review',
      // ...
      transitions: [
        defineTransition({
          name: 'to-approved',
          title: 'Approve and finish',
          to: 'approved',
          when: '$readyToApprove',
        }),
      ],
    }),
    // approved is unchanged
  ],
})

Deploy and repeat the check. The behavior is unchanged: the instance waits in review until legalApproved is true.

Control when a review can start

Starting has two decisions. start.filter controls discovery: which documents a surface such as Sanity Studio offers the workflow for. It does not gate startInstance. start.requirements is an ordered list of checks that every fresh standalone start must pass. Start block lists the complete interfaces.

export const articleReview = defineWorkflow({
  name: 'article-review',
  // ...
  fields: [
    defineField({
      type: 'subject',
      name: 'subject',
      title: 'Article',
      types: ['article'],
      required: true,
      initialValue: {type: 'input'},
    }),
    defineField({type: 'string', name: 'brief', title: 'Brief', initialValue: {type: 'input'}}),
  ],
  start: {
    filter: 'defined(title)',
    requirements: [
      {
        type: 'singleSubject',
        name: 'one-open-review',
        title: 'Review already in progress',
      },
      {
        type: 'groq',
        name: 'brief-required',
        title: 'Brief required',
        query: 'defined($fields.brief)',
      },
    ],
  },
  // stages are unchanged
})

types: ['article'] makes this workflow available for articles, and the filter narrows discovery to articles with a title. A start succeeds only when no unfinished run of this definition holds the same subject and the caller supplies a brief. Start requirements are not evaluated when you resume an unfinished start, or when a parent spawns a child.

A start.filter that reads the candidate document requires a subject field. A GROQ start requirement cannot read the candidate document at all, and its $fields holds the raw inputs, so a document reference is {id, type}, not a loaded document.

Deploy, then start an instance without --field brief=.... The CLI prints the requirement’s title:

✖ Start rejected
✖ start error:
  startInstance refused definition "article-review": Brief required. Pre-flight the verdict with evaluateStart.

Start again with --field brief="Launch post" and the instance starts. Run the same command a second time with the same subject and the singleSubject requirement refuses it with startInstance refused definition "article-review": Review already in progress. The rule applies across deployed versions of this definition, but a different definition does not count. It needs one subject field with initialValue: {type: 'input'}, and it compares subjects by their full global document reference, so documents in different datasets that share an _id never block each other. Completing the existing run permits another start.

Detect a return visit to a stage

Inside a condition, * searches the snapshot, not the Content Lake. Use the condition variables when they hold what you need, and query the raw instance only for state they do not expose, such as stage-visit history. Add this transition to review, before to-approved:

defineTransition({
  name: 'approve-after-rework',
  title: 'Approve a reworked article',
  to: 'approved',
  // $stage == "review" is true on every visit.
  // Count the stored review entries to detect a return visit.
  when: '$allActivitiesDone && count(*[_id == $self][0].stages[name == "review"]) > 1',
})

$stage names the current stage and is true on every visit to review; there is no $stages history variable. The $self query counts the stored stage entries, so it tells a return visit apart. Keep $allActivitiesDone in the condition: without it, the transition fires the moment the instance re-enters review, before anyone signs off.

To check it, deploy, start an instance with a brief, submit it, and send it back with npx sanity-workflows set-stage INSTANCE_ID --to drafting. Submit again and approve: the instance reaches approved without legalApproved, through approve-after-rework.

Next steps

Visiting agent?

Was this page helpful?

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