Skip to main content
Workflows are composable, transactional business processes in Medusa. They allow you to build complex operations from reusable steps with automatic compensation (rollback) on failure.

What is a Workflow?

A workflow is:
  • A sequence of steps that execute in order
  • Transactional - all steps succeed or all are rolled back
  • Composable - workflows can call other workflows
  • Asynchronous - steps can run in the background
  • Type-safe - fully typed inputs and outputs

Creating Your First Workflow

1

Create a Step

Steps are the building blocks of workflows. Each step has an invocation function and optional compensation function:
src/workflows/brand/steps/create-brand.ts
The StepResponse takes two arguments:
  1. The output of the step (returned to the workflow)
  2. Data to pass to the compensation function if rollback is needed
2

Create the Workflow

Compose steps into a workflow using createWorkflow:
src/workflows/brand/create-brand.ts
3

Use the Workflow

Execute the workflow from an API route or another workflow:
src/api/admin/brands/route.ts

Advanced Workflow Patterns

Multiple Steps with Compensation

Here’s a complete example showing multiple steps with compensation:
src/workflows/brand/steps/delete-brand.ts
src/workflows/brand/delete-brand.ts

Transform Data Between Steps

Use transform to manipulate data between steps:

Conditional Execution

Use when to conditionally execute steps:

Parallel Execution

Use parallelize to run independent steps concurrently:

Query Data in Workflows

Use useQueryGraphStep to fetch data:

Step Context

The step context provides access to:
  • container - Dependency injection container
  • context - Shared context across steps
  • metadata - Additional metadata
  • idempotencyKey - Unique key for idempotent execution

Error Handling

Workflows automatically handle errors and trigger compensation:
When a step throws an error, all previously executed steps run their compensation functions in reverse order.

Workflow Hooks

Hooks allow you to emit events when a workflow completes:
Subscribe to hooks in subscribers (see Event Subscribers).

Best Practices

  • Keep steps focused on a single responsibility
  • Always provide compensation functions for steps that modify data
  • Use transform for data manipulation instead of complex logic in steps
  • Name steps and workflows descriptively
  • Type your inputs and outputs for type safety
  • Use parallelize for independent operations
  • Handle errors with proper MedusaError types
  • Test workflows in isolation

Next Steps

Create API Routes

Build HTTP endpoints that use workflows

Event Subscribers

React to workflow events and hooks