Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 33 ยท Workflows

Hooks and Built-in Workflows

Use Medusa's core workflows such as createProductsWorkflow and completeCartWorkflow, extend them with hooks and validate hooks, and know when to wrap instead.

Medusa's own commerce features are built from the same workflows you write. Creating a product, completing a cart and placing an order are all workflows shipped in @medusajs/medusa/core-flows. That has two big consequences: you can call them from your own code instead of reimplementing them, and you can extend them through hooks without forking anything.

In this lesson you meet the most important built-in workflows, learn how hooks and validate hooks work, and learn the rule for choosing between hooking into a workflow and wrapping it in a new one. The Medusa code is read-only; the stand-ins model a workflow with hook points so you can see the extension mechanism.

Calling a built-in workflow

Core workflows are imported by name and run exactly like your own (Workflows and Steps). Here is a read-only example of creating a product from a custom route, with the shape of the input following the Admin API:

TypeScript
import { createProductsWorkflow } from "@medusajs/medusa/core-flows"

const { result } = await createProductsWorkflow(req.scope).run({
  input: {
    products: [
      {
        title: "Linen Shirt",
        status: "draft",
        options: [{ title: "Size", values: ["S", "M", "L"] }],
        variants: [
          {
            title: "S",
            options: { Size: "S" },
            prices: [{ currency_code: "usd", amount: 4500 }],
          },
        ],
      },
    ],
  },
})

The built-in workflow does everything the Admin would: creates the product and variants, prices, links to a sales channel when requested, and emits events. Calling it from your own route or job means your custom entry points behave identically to the dashboard.

A few workflows you will use often:

Workflow What it does
createProductsWorkflow Creates products with variants, options and prices
updateProductsWorkflow Updates products and variants
createCartWorkflow, addToCartWorkflow Starts a cart and adds line items
completeCartWorkflow Turns a cart into an order, authorizing payment and reserving inventory
createOrderWorkflow Creates an order directly (for example for imports or draft flows)
createCustomersWorkflow Creates customers

Names and input shapes change between Medusa versions, so check the reference for the version you installed. The pattern is what matters: a single entry point for a business operation that other code reuses.

What a hook is

A workflow author can mark hook points: named places where the workflow pauses to let outside code run, passing it the current data. You register a hook handler for that name in a file under src/workflows/hooks/. The workflow itself stays untouched.

flowchart LR
    S1["validate"] --> S2["create products"] --> H["hook:<br/>productsCreated"] --> S3["link and emit events"]
    H -. "your handler" .-> X["custom code"]

A hook is a gap in the workflow that other code can fill, with the workflow's data passed in.

Hooks are not events. An event subscriber runs after the fact, outside the workflow, and cannot make the workflow fail (Events and Subscribers). A hook handler runs inside the workflow's transaction: if it throws, the workflow fails and earlier steps are compensated. It can also supply its own compensation function.

Registering a hook handler

This real, read-only example saves a brand_id sent along with a new product. The first function is the handler; the optional second function is its compensation:

TypeScript
// src/workflows/hooks/created-product.ts
import { createProductsWorkflow } from "@medusajs/medusa/core-flows"
import { Modules } from "@medusajs/framework/utils"
import { StepResponse } from "@medusajs/framework/workflows-sdk"

createProductsWorkflow.hooks.productsCreated(
  async ({ products, additional_data }, { container }) => {
    if (!additional_data?.brand_id) {
      return new StepResponse([], [])
    }

    const link = container.resolve("link")
    const links = products.map((product) => ({
      [Modules.PRODUCT]: { product_id: product.id },
      brand: { brand_id: additional_data.brand_id },
    }))
    await link.create(links)

    return new StepResponse(links, links)
  },
  async (links, { container }) => {
    if (!links?.length) {
      return
    }
    await container.resolve("link").dismiss(links)
  }
)

The handler receives the workflow's data at that point (products, here) and additional_data, a free-form object the caller can attach to the request. The link logic uses the API from Module Links. Returning a StepResponse with compensation input lets the engine undo the links if a later step fails.

Letting additional_data through

Workflows that accept extra data expect it to be validated. For built-in HTTP routes you declare the shape in src/api/middlewares.ts with a Zod schema, so the route accepts additional_data and passes it into the workflow. Without that, unknown fields are rejected. This keeps customization explicit and typed, and is covered with the rest of validation in Custom API Routes and Middleware.

Validate hooks

Many workflows expose a validate hook that runs before any changes are made. Throw there to reject the operation early, with nothing to undo:

TypeScript
import { completeCartWorkflow } from "@medusajs/medusa/core-flows"
import { MedusaError } from "@medusajs/framework/utils"

completeCartWorkflow.hooks.validate(async ({ input, cart }) => {
  if (cart.metadata?.requires_age_check && !cart.metadata?.age_verified) {
    throw new MedusaError(
      MedusaError.Types.NOT_ALLOWED,
      "Age verification is required before checkout"
    )
  }
})

Which data the validate hook receives differs per workflow, so read the reference for the one you extend. Validation is cheap and safe; do as much of it here as you can instead of discovering a problem after money moved.

Hook or wrap?

You have two ways to customize a built-in operation. Use this rule:

  • Use a hook when your change belongs inside the operation and must succeed or fail with it: saving extra fields, adding validation, linking custom data, writing an audit row that must exist whenever a product exists.
  • Wrap (write a new workflow that calls the built-in one as a step) when you need to run steps before or around it, call different workflows by condition, or compose several built-ins into a bigger operation. Call a built-in workflow from inside another with .runAsStep({ input }).
  • Use an event subscriber when the reaction can happen later and must not block or fail the original operation, such as sending a welcome email.

Hooks are limited to the points the workflow author chose; you cannot insert code anywhere. If no hook exists where you need one, wrap, or open an issue upstream.

Stand-in 1: a workflow with hook points

The real hook system registers handlers by name before the workflow runs. This stand-in does the same: the workflow declares hook names, outside code registers handlers, and a failing handler triggers compensation of both the earlier steps and the handlers that already ran.

JS Hook points inside a mini workflow

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

No output.

The empty title was rejected before anything was created. The "Wool Hat" product was created, its hook handler threw, and the engine removed the product again, so only the shirt and its link remain.

Stand-in 2: wrapping versus hooking

Hooks run inside the built-in workflow; a wrapper runs around it. This second stand-in shows both extension styles on a simple built-in "place order" function, so you can see where each kind of code executes.

JS Hook inside versus wrapper around

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

No output.

The hook code ran in the middle of the built-in flow, while the wrapper code ran before and after it. If the order is created the hook has already written its audit row; the wrapper's note is attached only after the built-in operation returns.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main difference between a workflow hook and an event subscriber?

    Hooks execute within the workflow's transaction, so throwing there fails the workflow and triggers compensation. Subscribers run outside it and cannot undo the original operation.
  2. 2. Where is a validate hook best used?

    Validate hooks run first. Throwing there rejects the operation before anything has been changed, so nothing needs undoing.
  3. 3. You need to run extra steps before calling completeCartWorkflow and choose between workflows by condition. What fits best?

    Wrapping lets you add logic around the built-in workflow. Hooks only run at the points the workflow author exposed.
  4. 4. What does additional_data allow?

    Callers can attach additional data (validated through middleware schemas), and hook handlers receive it to save or act on.

Summary

  • Core workflows in @medusajs/medusa/core-flows are the same ones the Admin uses; call them from your own routes and jobs.
  • Hooks are named gaps that run your handler inside the workflow, with optional compensation; validate hooks run first.
  • Custom request data travels in additional_data, declared and validated in src/api/middlewares.ts.
  • Hook for changes that belong inside the operation, wrap for steps before or around it, and subscribe for later, non-blocking reactions.
  • Check workflow names, input shapes and hook names against your installed Medusa version.

Next: Events and Subscribers