Middlewares allow you to intercept and respond to workflow lifecycle events and debug messages. They're useful for logging, monitoring, error tracking, and custom integrations.
Overview#
A middleware can hook into:
- Lifecycle Events: Run started, run completed, before/after step execution
- Debug Events: Errors, warnings, and info messages
Built-in Middleware#
Upstash Workflow provides a built-in logging middleware that you can use out of the box:
The logging middleware outputs detailed execution logs to your application's console, including:
- When workflow runs start and complete
- Before and after each step execution
- Error, warning, and info messages
Creating Custom Middleware#
You can create your own middleware by instantiating a WorkflowMiddleware class.
Using Direct Callbacks#
The simplest way to create a middleware is by providing callbacks directly:
Using Init Function#
For middlewares that need to initialize resources (like database connections or external clients), use the init pattern:
Event Types#
Lifecycle Events#
Called when a workflow run begins.
Parameters:
context: The workflow context
Called before each step executes.
Parameters:
context: The workflow contextstepName: Name of the step about to execute
Called after each step completes.
Parameters:
context: The workflow contextstepName: Name of the completed stepresult: The result returned by the step
Called when the entire workflow run finishes.
Parameters:
context: The workflow contextresult: The final result of the workflow
Debug Events#
Called when an error occurs.
Parameters:
workflowRunId: The workflow run ID (optional)error: The error object
Called when a warning is logged.
Parameters:
workflowRunId: The workflow run ID (optional)warning: The warning message
Called when an info message is logged.
Parameters:
workflowRunId: The workflow run ID (optional)info: The info message
Examples#
Error Tracking Middleware#
Send errors to an external monitoring service:
Multiple Middlewares#
You can use multiple middlewares together:
Middlewares are executed in the order they're provided in the array.