> For AI agents: the complete Sanity documentation index is available at [https://www.sanity.io/docs/llms.txt](https://www.sanity.io/docs/llms.txt).

# Cookbook: Client–server asset intake

Start an image-review workflow from an app, then let a server import or discard the staged file.

> [!WARNING]
> Early access
> Workflows is in early access, built in public. Read [How early access works](https://www.sanity.io/docs/workflows/prerelease) before you rely on it.



Use this recipe when an app collects an image for human review but an authenticated server must perform the privileged import or deletion. The app starts one Workflows instance for an assetIntakeRequest document, which is the workflow subject.

## The workflow

![Asset intake stages: Review branches to Importing, Awaiting replacement, or Discarding. Importing can finish as Accepted or return to Review; Discarding can finish as Rejected or return to Review; a replacement returns to Review.](https://cdn.sanity.io/images/3do82whm/next/4915a21f2dc22bd246c813057eeba95b6e2e1535-2176x1240.png)

1. Review: a reviewer accepts, requests a replacement, or rejects the image.
2. Awaiting replacement: the instance waits until the application records a new upload and fires `resume-review`.
3. Importing: the server imports an accepted image. After a successful import, the engine moves the instance to Accepted; after a failed import, back to Review.
4. Discarding: the server deletes a rejected staged image. After a successful deletion, the engine moves the instance to Rejected; after a failed deletion, back to Review.
5. Accepted: terminal. The imported image is ready for downstream use.
6. Rejected: terminal. The staged image has been discarded.

## Before you get started

- Packages: `@sanity/workflows`, `@sanity/workflows-ui`, and `@sanity/client`.
- An upload flow that places the file in temporary storage and creates an assetIntakeRequest document.
- An authenticated app client, a server-side Sanity client, and an adapter for temporary file storage. Keep storage credentials and privileged Sanity tokens on the server.

## Define the workflow

The engine fires the `reset` action each time the instance enters Review, which clears the previous decision. Without it, after a failed import the engine would read the old accept decision and move the instance straight back to Importing.

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

export const assetIntake = defineWorkflow({
  name: 'asset-intake',
  title: 'Asset intake',
  initialStage: 'review',
  fields: [
    defineField({type: 'subject', name: 'subject', initialValue: {type: 'input'}, required: true}),
    defineField({type: 'actor', name: 'reviewer'}),
    defineField({type: 'string', name: 'decision'}),
    defineField({type: 'string', name: 'reviewNote'}),
    defineField({type: 'string', name: 'importOutcome'}),
    defineField({type: 'string', name: 'discardOutcome'}),
    defineField({type: 'string', name: 'assetId'}),
  ],
  stages: [
    defineStage({
      name: 'review',
      title: 'Review',
      activities: [
        defineActivity({
          name: 'review',
          title: 'Review submission',
          actions: [
            defineAction({
              name: 'reset',
              when: 'true',
              ops: [
                {type: 'field.unset', target: {field: 'decision'}},
                {type: 'field.unset', target: {field: 'importOutcome'}},
                {type: 'field.unset', target: {field: 'discardOutcome'}},
              ],
            }),
            defineAction({
              name: 'claim',
              title: 'Take review',
              filter: '!defined($fields.reviewer)',
              ops: [{type: 'field.set', target: {field: 'reviewer'}, value: {type: 'actor'}}],
            }),
            defineAction({
              name: 'accept',
              title: 'Accept',
              status: 'done',
              filter: '$fields.reviewer.id == $actor.id',
              ops: [
                {
                  type: 'field.set',
                  target: {field: 'decision'},
                  value: {type: 'literal', value: 'accept'},
                },
              ],
            }),
            defineAction({
              name: 'request-replacement',
              title: 'Request replacement',
              status: 'done',
              filter: '$fields.reviewer.id == $actor.id',
              params: [{type: 'string', name: 'note', title: 'What needs changing?', required: true}],
              ops: [
                {
                  type: 'field.set',
                  target: {field: 'decision'},
                  value: {type: 'literal', value: 'replace'},
                },
                {
                  type: 'field.set',
                  target: {field: 'reviewNote'},
                  value: {type: 'param', param: 'note'},
                },
              ],
            }),
            defineAction({
              name: 'reject',
              title: 'Reject',
              status: 'done',
              filter: '$fields.reviewer.id == $actor.id',
              ops: [
                {
                  type: 'field.set',
                  target: {field: 'decision'},
                  value: {type: 'literal', value: 'reject'},
                },
              ],
            }),
          ],
        }),
      ],
      transitions: [
        defineTransition({name: 'to-importing', to: 'importing', when: "$fields.decision == 'accept'"}),
        defineTransition({name: 'to-awaiting-replacement', to: 'awaiting-replacement', when: "$fields.decision == 'replace'"}),
        defineTransition({name: 'to-discarding', to: 'discarding', when: "$fields.decision == 'reject'"}),
      ],
    }),
    defineStage({
      name: 'awaiting-replacement',
      title: 'Awaiting replacement',
      activities: [
        defineActivity({
          name: 'replacement',
          title: 'Replacement received',
          actions: [defineAction({name: 'resume-review', title: 'Resume review', status: 'done'})],
        }),
      ],
      transitions: [defineTransition({name: 'to-review', to: 'review', when: '$allActivitiesDone'})],
    }),
    defineStage({
      name: 'importing',
      title: 'Importing',
      activities: [
        defineActivity({
          name: 'import',
          title: 'Import image',
          actions: [
            defineAction({
              name: 'run',
              when: 'true',
              effects: [
                {
                  name: 'asset-intake.import',
                  bindings: {subject: '$fields.subject._id'},
                  outputs: [{type: 'string', name: 'assetId'}],
                },
              ],
            }),
            defineAction({
              name: 'finished',
              status: 'done',
              when: "$effectStatus['asset-intake.import'] == 'done'",
            }),
          ],
        }),
      ],
      transitions: [
        defineTransition({name: 'to-accepted', to: 'accepted', when: "$allActivitiesDone && $fields.importOutcome == 'ok'"}),
        defineTransition({name: 'back-to-review', to: 'review', when: "$allActivitiesDone && $fields.importOutcome == 'failed'"}),
      ],
    }),
    defineStage({
      name: 'discarding',
      title: 'Discarding',
      activities: [
        defineActivity({
          name: 'discard',
          title: 'Discard staged image',
          actions: [
            defineAction({
              name: 'run',
              when: 'true',
              effects: [{name: 'asset-intake.discard', bindings: {subject: '$fields.subject._id'}}],
            }),
            defineAction({
              name: 'finished',
              status: 'done',
              when: "$effectStatus['asset-intake.discard'] == 'done'",
            }),
          ],
        }),
      ],
      transitions: [
        defineTransition({name: 'to-rejected', to: 'rejected', when: "$allActivitiesDone && $fields.discardOutcome == 'ok'"}),
        defineTransition({name: 'back-to-review', to: 'review', when: "$allActivitiesDone && $fields.discardOutcome == 'failed'"}),
      ],
    }),
    defineStage({name: 'accepted', title: 'Accepted'}),
    defineStage({name: 'rejected', title: 'Rejected'}),
  ],
})
```

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](https://www.sanity.io/docs/workflows/fields) to add one.

## Deploy the definition

A reader model is the lowest stored-data model version an engine must support to read a definition. This workflow requires reader model 13 because its triggers read `$effectStatus`. Its required subject alone would need 10. Upgrade every runtime sharing the workflow resource before setting `expectedMinReaderModel` to `13` and deploying. Follow the model-13 rollout in [Upgrade Workflows packages](https://www.sanity.io/docs/workflows/upgrade).

**sanity.workflow.ts**

```typescript
import {defineWorkflowConfig} from '@sanity/workflows/define'
import {assetIntake} from './asset-intake'

export default defineWorkflowConfig({
  deployments: [
    {
      name: 'production',
      partition: 'production',
      workflowResource: {type: 'dataset', id: 'your-project.workflows'},
      expectedMinReaderModel: 13,
      definitions: [assetIntake],
    },
  ],
})
```

Deploy this configuration with the Workflows CLI, then run the client and server against the same workflow resource and partition.

## Build the client

Build the client engine from the authenticated Sanity client your app already owns. After the upload flow creates the assetIntakeRequest document, call startAssetIntake with its resource-qualified reference. The returned instance ID opens the review session.

```typescript
import type {SanityClient} from '@sanity/client'
import {createEngine, type GlobalDocumentReference} from '@sanity/workflows'

export function createClientEngine(client: SanityClient) {
  return createEngine({
    client,
    workflowResource: {type: 'dataset', id: 'your-project.workflows'},
    partition: 'production',
  })
}

export async function startAssetIntake(
  engine: ReturnType<typeof createClientEngine>,
  request: GlobalDocumentReference,
): Promise<string> {
  const {instance} = await engine.startInstance({
    definition: 'asset-intake',
    initialFields: [{type: 'subject', name: 'subject', value: request}],
  })
  return instance._id
}
```

The reviewer first selects Take review, then Accept or Reject. Render only actions available in the evaluation. After a successful decision, the app sends a request that wakes the authenticated server; if that request is lost, a server listener must wake the server instead.

**ReviewPanel.tsx**

```tsx
import {useState} from 'react'
import {actionRendering, errorMessage, type Engine} from '@sanity/workflows'
import {useWorkflowSession, type WorkflowSession} from '@sanity/workflows-ui/sdk'

type ReviewAction = 'claim' | 'accept' | 'reject'

export async function submitReviewAction(
  fireAction: WorkflowSession['fireAction'],
  instanceId: string,
  action: ReviewAction,
) {
  await fireAction({activity: 'review', action})
  if (action === 'claim') return

  const response = await fetch('/api/asset-intake/drain', {
    method: 'POST',
    headers: {'content-type': 'application/json'},
    body: JSON.stringify({instanceId}),
  })
  if (!response.ok) throw new Error('Decision saved; could not wake the server')
}

export function ReviewPanel({engine, instanceId}: {engine: Engine; instanceId: string}) {
  const {evaluation, ready, fireAction} = useWorkflowSession({engine, instanceId})
  const [pending, setPending] = useState(false)
  const [error, setError] = useState<string>()
  if (!ready || !evaluation) return null

  const actions = evaluation.currentStage.activities
    .find(({activity}) => activity.name === 'review')?.actions ?? []

  async function submit(action: ReviewAction) {
    setPending(true)
    setError(undefined)
    try {
      await submitReviewAction(fireAction, instanceId, action)
    } catch (cause) {
      setError(errorMessage(cause))
    } finally {
      setPending(false)
    }
  }

  return (
    <section>
      <p>Stage: {evaluation.currentStage.stage.title}</p>
      {(['claim', 'accept', 'reject'] as const).map((name) => {
        const action = actions.find((entry) => entry.action.name === name)
        if (!action || actionRendering(action) !== 'button') return null
        return (
          <button key={name} type="button" disabled={pending || !action.allowed}
            onClick={() => submit(name)}>
            {action.action.title ?? name}
          </button>
        )
      })}
      {error ? <p role="alert">{error}</p> : null}
    </section>
  )
}
```

## Build the server

Keep the storage integration behind a small adapter. Its implementation may upload to a Sanity dataset, call an internal asset service, or target another storage product. Both operations must deduplicate by idempotencyKey.

```typescript
export type ImportResult = {assetId: string}

export interface IntakeService {
  importImage(args: {requestId: string; idempotencyKey: string}): Promise<ImportResult>
  discardImage(args: {requestId: string; idempotencyKey: string}): Promise<void>
}

export const intakeService: IntakeService = {
  async importImage() {
    throw new Error('Connect this adapter to your staged-file service')
  },
  async discardImage() {
    throw new Error('Connect this adapter to your staged-file service')
  },
}
```

Each effect concern gets its own handler. The import handler records the new asset ID and an outcome. The discard handler records only its outcome.

```typescript
import {extractDocumentId} from '@sanity/workflows'

export function subjectId(params: Record<string, unknown>): string {
  if (typeof params.subject !== 'string') throw new Error('Missing subject binding')
  return extractDocumentId(params.subject)
}
```

```typescript
import type {EffectHandler} from '@sanity/workflows'
import {intakeService} from '../intake-service'
import {subjectId} from './subject'

export const importImage: EffectHandler = async (params, ctx) => {
  try {
    const result = await intakeService.importImage({
      requestId: subjectId(params),
      idempotencyKey: ctx.effectKey,
    })
    return {
      outputs: {assetId: result.assetId},
      ops: [
        {
          type: 'field.set',
          target: {scope: 'workflow', field: 'assetId'},
          value: {type: 'literal', value: result.assetId},
        },
        {
          type: 'field.set',
          target: {scope: 'workflow', field: 'importOutcome'},
          value: {type: 'literal', value: 'ok'},
        },
      ],
    }
  } catch (error) {
    ctx.log('Image import failed', {message: error instanceof Error ? error.message : String(error)})
    return {
      ops: [
        {
          type: 'field.set',
          target: {scope: 'workflow', field: 'importOutcome'},
          value: {type: 'literal', value: 'failed'},
        },
      ],
    }
  }
}
```

```typescript
import type {EffectHandler} from '@sanity/workflows'
import {intakeService} from '../intake-service'
import {subjectId} from './subject'

export const discardImage: EffectHandler = async (params, ctx) => {
  try {
    await intakeService.discardImage({
      requestId: subjectId(params),
      idempotencyKey: ctx.effectKey,
    })
    return {
      ops: [
        {
          type: 'field.set',
          target: {scope: 'workflow', field: 'discardOutcome'},
          value: {type: 'literal', value: 'ok'},
        },
      ],
    }
  } catch (error) {
    ctx.log('Staged image discard failed', {message: error instanceof Error ? error.message : String(error)})
    return {
      ops: [
        {
          type: 'field.set',
          target: {scope: 'workflow', field: 'discardOutcome'},
          value: {type: 'literal', value: 'failed'},
        },
      ],
    }
  }
}
```

Assemble the named handlers in one registry, then give that registry to the server engine.

```typescript
import type {EffectHandler} from '@sanity/workflows'
import {discardImage} from './discard-image'
import {importImage} from './import-image'

export const effectHandlers: Record<string, EffectHandler> = {
  'asset-intake.import': importImage,
  'asset-intake.discard': discardImage,
}
```

```typescript
import {createClient} from '@sanity/client'
import {createEngine, ENGINE_API_VERSION} from '@sanity/workflows'
import {effectHandlers} from './handlers/index'

const client = createClient({
  projectId: 'your-project',
  dataset: 'workflows',
  apiVersion: ENGINE_API_VERSION,
  token: process.env.SANITY_AUTH_TOKEN,
  useCdn: false,
})

export const serverEngine = createEngine({
  client,
  workflowResource: {type: 'dataset', id: 'your-project.workflows'},
  partition: 'production',
  effects: {handlers: effectHandlers},
})
```

Expose a small drain function through your existing authenticated server route. Validate and authorize the request before passing its instance ID here. Engine action filters are advisory; the server route and the systems it calls remain the security boundary.

```typescript
import {serverEngine} from './engine.server'

export async function drainAssetIntake(instanceId: string): Promise<void> {
  await serverEngine.drainEffects({instanceId})
}
```

## Follow a submission and acceptance

The client app gives the reviewer the Review actions, then wakes the authenticated server after acceptance. The engine makes the transitions from Review to Importing and Accepted; the Content Lake persists each state.

![A client app starts the image workflow in Review and shows it to a reviewer. Acceptance moves it to Importing. An authenticated server drains the import effect, after which the engine moves the workflow to Accepted. The Content Lake persists each state.](https://cdn.sanity.io/images/3do82whm/next/caf3397be2baa6690d24f33eb9372ed5034504cf-2800x1964.png)

1. The upload flow stores the file, creates an assetIntakeRequest document, and starts the asset-intake workflow with that document as its subject.
2. The instance begins in Review. The review surface receives the instance ID and watches it for updates.
3. The reviewer selects Take review, then Accept. The engine moves the instance to Importing and queues the import effect.
4. The app wakes the server, which calls `drainEffects`. The engine runs the import handler, which imports the image once and records the asset ID and outcome.
5. The engine moves the instance to Accepted, and the review surface updates automatically.

## Handle failures

- Action commit fails: no effect is queued. Show the commit error and let the reviewer retry.
- Wake-up request fails: the effect remains pending. The server listener can still drain it.
- Import or discard fails: the handler records a failed outcome, and the engine moves the instance back to Review.
- A handler runs twice: the service deduplicates the external operation with ctx.effectKey.

Do not expose a public endpoint that accepts arbitrary instance IDs and drains them with a privileged token. Authenticate the caller, authorize the instance, and restrict the server engine to the intended workflow resource and partition.

## Adapt the pattern

The domain is deliberately ordinary Sanity image intake. To target Media Library, replace the intake-service adapter and route the subject client to that resource; the workflow and client–server boundary stay the same.

Use this split when an interactive app handles the person’s action and a server holds the secrets. If no app needs to wake the operation, a Sanity Function that calls `drainEffects` for the same server effects is the smaller architecture.

> [!NOTE]
> Visiting agent?
> Workflows has MCP tools that let an agent inspect, operate, author, validate, and deploy workflows. An agent host embeds these tools. Ask the person you work for whether your host [includes the Workflows tools](https://www.sanity.io/docs/workflows/mcp).



