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>>:
| Property | Type | Description |
|---|---|---|
eventData | T | The data payload sent with the event. null if timed out. |
timeout | boolean | true if the wait period expired before an event was received. |
Configuration
| Option | Type | Default | Description |
|---|---|---|---|
timeout | Duration | 24h | Maximum time to wait for the event. |
How it Works
- When
waitForEventis called, the workflow execution is suspended. - Stepflow creates a subscription for the
eventIdin the storage backend. - If a timeout is provided, a timeout job is scheduled.
- When
notifyorsendEventis called with a matchingeventId, the workflow is resumed with the event data. - If the timeout is reached first, the workflow is resumed with
timeout: true.