Skip to main content
Mastra v1 is coming in January 2026. Get ahead by starting new projects with the beta or upgrade your existing project today.

Workflow.if()

Experimental

The .if() method creates a conditional branch in the workflow, allowing steps to execute only when a specified condition is true. This enables dynamic workflow paths based on the results of previous steps.

UsageDirect link to Usage

workflow
.step(startStep)
.if(async ({ context }) => {
const value = context.getStepResult<{ value: number }>("start")?.value;
return value < 10; // If true, execute the "if" branch
})
.then(ifBranchStep)
.else()
.then(elseBranchStep)
.commit();

ParametersDirect link to Parameters

condition:

Function | ReferenceCondition
A function or reference condition that determines whether to execute the 'if' branch

Condition TypesDirect link to Condition Types

Function ConditionDirect link to Function Condition

You can use a function that returns a boolean:

workflow
.step(startStep)
.if(async ({ context }) => {
const result = context.getStepResult<{ status: string }>("start");
return result?.status === "success"; // Execute "if" branch when status is "success"
})
.then(successStep)
.else()
.then(failureStep);

Reference ConditionDirect link to Reference Condition

You can use a reference-based condition with comparison operators:

workflow
.step(startStep)
.if({
ref: { step: startStep, path: "value" },
query: { $lt: 10 }, // Execute "if" branch when value is less than 10
})
.then(ifBranchStep)
.else()
.then(elseBranchStep);

ReturnsDirect link to Returns

workflow:

LegacyWorkflow
The workflow instance for method chaining

Error HandlingDirect link to Error Handling

The if method requires a previous step to be defined. If you try to use it without a preceding step, an error will be thrown:

try {
// This will throw an error
workflow
.if(async ({ context }) => true)
.then(someStep)
.commit();
} catch (error) {
console.error(error); // "Condition requires a step to be executed after"
}