3.6.6. Expose a Workflow Hook

In this chapter, you'll learn how to expose a hook in your workflow.

When to Expose a Hook#

Expose workflow hooks whenYour workflow is reusable in other applications, and you allow performing an external action at some point in your workflow.
Don't expose workflow hooks ifYour workflow isn't reusable by other applications. Use a step that performs what a hook handler would instead.

How to Expose a Hook in a Workflow?#

To expose a hook in your workflow, use createHook from the Workflows SDK.

For example:

src/workflows/my-workflow/index.ts
1import {2  createStep,3  createHook,4  createWorkflow,5  WorkflowResponse,6} from "@medusajs/framework/workflows-sdk"7import { createProductStep } from "./steps/create-product"8
9export const myWorkflow = createWorkflow(10  "my-workflow", 11  function (input) {12    const product = createProductStep(input)13    const productCreatedHook = createHook(14      "productCreated", 15      { productId: product.id }16    )17
18    return new WorkflowResponse(product, {19      hooks: [productCreatedHook],20    })21  }22)

The createHook function accepts two parameters:

  1. The first is a string indicating the hook's name. You use this to consume the hook later.
  2. The second is the input to pass to the hook handler.

The workflow must also pass an object having a hooks property as a second parameter to the WorkflowResponse constructor. Its value is an array of the workflow's hooks.

How to Consume the Hook?#

To consume the hook of the workflow, create the file src/workflows/hooks/my-workflow.ts with the following content:

src/workflows/hooks/my-workflow.ts
1import { myWorkflow } from "../my-workflow"2
3myWorkflow.hooks.productCreated(4  async ({ productId }, { container }) => {5    // TODO perform an action6  }7)

The hook is available on the workflow's hooks property using its name productCreated.

You invoke the hook, passing a step function (the hook handler) as a parameter.

Was this chapter helpful?
Edit this page