Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 33 ยท Workflows

Workflows and Steps

Learn how Medusa workflows chain steps with createStep, createWorkflow, transform and WorkflowResponse, and why they replace chains of service calls.

Most useful commerce operations touch more than one thing. Creating a product might also create prices, link it to a sales channel and reserve nothing at all if something fails. If you write that as a handful of service calls in an API route, a failure halfway leaves the database in a state nobody planned for. Medusa's answer is the workflow: a named, ordered list of steps with defined inputs and outputs, run by a framework that knows how to track and undo them.

This lesson covers the building blocks: createStep, createWorkflow, transform, WorkflowResponse, how to run a workflow from a route, and what changes compared with plain service calls. Rolling back and long-running steps come in the next lesson. The real Medusa code is read-only; the stand-ins build a small step runner so the model becomes concrete.

A workflow is a recipe, not a function call

A workflow has two phases that beginners often mix up.

  1. Definition. When the server loads your file, the workflow's composer function runs once to describe the steps and how data flows between them. It builds a plan.
  2. Execution. Each time you call .run({ input }), the engine executes that plan with real data.

Because the composer only describes the plan, you cannot use ordinary JavaScript on step results inside it. A value returned by a step during definition is a placeholder, not the data. That is why transform exists.

flowchart LR
    I["input"] --> S1["step 1<br/>create product"]
    S1 --> T["transform<br/>build price payload"]
    T --> S2["step 2<br/>create prices"]
    S2 --> R["WorkflowResponse"]

Steps pass placeholders along; the engine fills them with real data at run time.

Writing a step

A step is created with createStep. It takes a name, an invoke function and, optionally, a compensation function (next lesson). The invoke function receives the step input and the context, which includes the container. It returns a StepResponse. This is real, read-only Medusa code:

TypeScript
import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
import { Modules } from "@medusajs/framework/utils"

type Input = { title: string }

export const createDraftProductStep = createStep(
  "create-draft-product",
  async (input: Input, { container }) => {
    const productService = container.resolve(Modules.PRODUCT)
    const [product] = await productService.createProducts([
      { title: input.title, status: "draft" },
    ])
    return new StepResponse(product, product.id)
  }
)

StepResponse takes two arguments: the step's output (given to later steps and the workflow result) and optional compensation input, a small piece of data handed to the undo function if the workflow fails later. Here we keep just the new product id because that is all deleting it needs.

Keep each step small and focused on one change. A step should do exactly one thing that can be undone on its own.

Composing steps into a workflow

createWorkflow takes a name and a composer function. The composer receives the workflow input and calls steps like ordinary functions:

TypeScript
import {
  createWorkflow,
  WorkflowResponse,
  transform,
} from "@medusajs/framework/workflows-sdk"

type WorkflowInput = { title: string; price: number }

export const createDraftWithPriceWorkflow = createWorkflow(
  "create-draft-with-price",
  (input: WorkflowInput) => {
    const product = createDraftProductStep({ title: input.title })

    const pricePayload = transform({ product, input }, (data) => ({
      product_id: data.product.id,
      amount: Math.round(data.input.price * 100),
    }))

    const prices = createProductPriceStep(pricePayload)

    return new WorkflowResponse({ product, prices })
  }
)

Points to notice:

  • product is not a real product while the composer runs. Writing product.id directly in the composer would not work as you expect; transform takes the placeholders you list and a plain function that runs at execution time with real values.
  • Steps run in the order they appear, unless you use helpers such as parallelize for independent steps.
  • WorkflowResponse wraps the value the caller receives. Anything not returned stays internal.
  • Conditions on step results use when(...), not a plain if, for the same reason: the plain if would run during definition.

Amounts are stored as integers in the smallest currency unit in Medusa's data model, so the example converts at the boundary; see Money as Integers for why.

Running a workflow

You run a workflow by calling the exported function with a container and then .run. In an API route the container is req.scope:

TypeScript
import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
import { createDraftWithPriceWorkflow } from "../../workflows/create-draft-with-price"

export async function POST(req: MedusaRequest, res: MedusaResponse) {
  const { result } = await createDraftWithPriceWorkflow(req.scope).run({
    input: { title: "Canvas Tote", price: 24.5 },
  })
  res.json(result)
}

By default, run throws if a step fails, after the engine has compensated completed steps. Pass throwOnError: false to receive { result, errors } instead, which is useful when you want to turn the failure into a specific HTTP response yourself. The same function also works inside subscribers, scheduled jobs and other workflows.

Why not just call services?

Compare the two styles.

Concern Service calls in a route Workflow
Failure halfway You must hand-write cleanup Completed steps are compensated
Reuse Copy the code to another route Call the workflow from anywhere
Extension Edit the original code Hooks let others add behavior (Hooks and Built-in Workflows)
Observability Logs you add yourself Each step is tracked by the engine
Long waits Hard Steps can be async (next lesson)

For one trivial single-module read or write, calling the module service directly is fine. Reach for a workflow as soon as the operation spans modules, needs undo, or other code may want to extend it. Reads belong to Query, not workflows (Query: Fields, Filters and Pagination).

Stand-in 1: a step runner

The real engine builds a graph from your composer. This stand-in uses the same idea in a few lines: createStep returns a function that records a node in the plan, transform records a deferred computation, and run resolves placeholders against real results. It is a teaching model, not Medusa's code.

JS createStep, createWorkflow and transform in 50 lines

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The composer ran once, at definition. The two run calls reused the same plan with different data, which is exactly why you must use transform for anything that depends on step results.

Stand-in 2: why placeholders matter

This short demo shows the mistake that transform prevents. A plain computation inside the composer runs at definition time, before any data exists.

JS Definition time versus run time

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Both runs return doubled: 0, because the multiplication happened once, during definition. In real Medusa you wrap that computation in transform so it runs for each execution.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When does the composer function passed to createWorkflow run?

    The composer builds the plan at definition time. The engine then executes that plan on every run with real data.
  2. 2. Why do you use transform instead of plain JavaScript on a step's result inside the composer?

    Step results do not exist until the workflow runs. transform defers your function so it receives the real values.
  3. 3. What are the two arguments of new StepResponse(output, compensationInput)?

    The first is the step output used by later steps and the result. The second is what compensation receives to undo that step.
  4. 4. Which operation is the best fit for a workflow?

    Workflows suit multi-step writes that need undo and reuse. Simple reads go through Query.

Summary

  • A workflow is a plan made of steps; the composer runs once at definition and the engine executes the plan on each run.
  • createStep defines one unit of work and returns a StepResponse with an output and optional compensation data.
  • Use transform for computations on step results, and when for conditions, because values are placeholders during definition.
  • Run a workflow with workflow(container).run({ input }); throwOnError: false returns { result, errors }.
  • Workflows beat chains of service calls when an operation spans modules, needs undo or should be extensible.
  • The stand-ins model the mechanics, not Medusa's real engine.

Next: Compensation, Rollback and Long-Running Workflows