StepflowStepflow

Wait for Event

Pause workflows until an external event occurs

Wait for Event

The ctx.waitForEvent() method allows a workflow to pause and wait for an external signal. This is commonly used for human-in-the-loop approvals, webhooks, or inter-workflow communication.

Basic Usage

To wait for an event, you need a unique eventId that the external system will use to signal the workflow.

const { eventData, timeout } = await ctx.waitForEvent(
  "wait-for-approval",
  `approval-${orderId}`,
  { timeout: "24h" },
);

if (timeout) {
  // Handle the case where no event was received within 24 hours
  return { status: "expired" };
}

// eventData contains the payload sent with the event
console.log("Received approval:", eventData);

Signaling a Workflow

There are two ways to send an event to a waiting workflow:

1. Using the Stepflow Instance

If you have access to the stepflow instance (e.g., in an API route), use stepflow.notify():

await stepflow.notify(`approval-${orderId}`, {
  approvedBy: "admin@example.com",
  timestamp: new Date(),
});

2. From Another Workflow

A workflow can signal another workflow using ctx.step.sendEvent():

await ctx.step.sendEvent(`approval-${orderId}`, {
  status: "approved",
});

Return Value

waitForEvent returns a Promise<WaitForEventResult<T>>:

PropertyTypeDescription
eventDataTThe data payload sent with the event. null if timed out.
timeoutbooleantrue if the wait period expired before an event was received.

Configuration

OptionTypeDefaultDescription
timeoutDuration24hMaximum time to wait for the event.

How it Works

  1. When waitForEvent is called, the workflow execution is suspended.
  2. Stepflow creates a subscription for the eventId in the storage backend.
  3. If a timeout is provided, a timeout job is scheduled.
  4. When notify or sendEvent is called with a matching eventId, the workflow is resumed with the event data.
  5. If the timeout is reached first, the workflow is resumed with timeout: true.

On this page