afterEvent()

The afterEvent() method creates a suspension point in your workflow that waits for a specific event to occur before continuing execution.

Syntax

workflow.afterEvent(eventName: string): Workflow

Parameters

ParameterTypeDescription
eventNamestringThe name of the event to wait for. Must match an event defined in the workflow’s events configuration.

Return Value

Returns the workflow instance for method chaining.

Description

The afterEvent() method is used to create an automatic suspension point in your workflow that waits for a specific named event. It’s essentially a declarative way to define a point where your workflow should pause and wait for an external event to occur.

When you call afterEvent(), Mastra:

  1. Creates a special step with ID __eventName_event
  2. This step automatically suspends the workflow execution
  3. The workflow remains suspended until the specified event is triggered via resumeWithEvent()
  4. When the event occurs, execution continues with the step following the afterEvent() call

This method is part of Mastra’s event-driven workflow capabilities, allowing you to create workflows that coordinate with external systems or user interactions without manually implementing suspension logic.

Usage Notes

  • The event specified in afterEvent() must be defined in the workflow’s events configuration with a schema
  • The special step created has a predictable ID format: __eventName_event (e.g., __approvalReceived_event)
  • Any step following afterEvent() can access the event data via context.inputData.resumedEvent
  • Event data is validated against the schema defined for that event when resumeWithEvent() is called

Examples

Basic Usage

// Define workflow with events
const workflow = new Workflow({
  name: 'approval-workflow',
  events: {
    approval: {
      schema: z.object({
        approved: z.boolean(),
        approverName: z.string(),
      }),
    },
  },
});
 
// Build workflow with event suspension point
workflow
  .step(submitRequest)
  .afterEvent('approval')    // Workflow suspends here
  .step(processApproval)     // This step runs after the event occurs
  .commit();