Skip to main content
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

runStarted
function
Called when a workflow run begins.Parameters:
  • context: The workflow context
beforeExecution
function
Called before each step executes.Parameters:
  • context: The workflow context
  • stepName: Name of the step about to execute
afterExecution
function
Called after each step completes.Parameters:
  • context: The workflow context
  • stepName: Name of the completed step
  • result: The result returned by the step
runCompleted
function
Called when the entire workflow run finishes.Parameters:
  • context: The workflow context
  • result: The final result of the workflow

Debug Events

onError
function
Called when an error occurs.Parameters:
  • workflowRunId: The workflow run ID (optional)
  • error: The error object
onWarning
function
Called when a warning is logged.Parameters:
  • workflowRunId: The workflow run ID (optional)
  • warning: The warning message
onInfo
function
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.