Upstash Documentation

Middlewares

2 min read

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#

runStartedfunction#

Called when a workflow run begins.

Parameters:

  • context: The workflow context
beforeExecutionfunction#

Called before each step executes.

Parameters:

  • context: The workflow context
  • stepName: Name of the step about to execute
afterExecutionfunction#

Called after each step completes.

Parameters:

  • context: The workflow context
  • stepName: Name of the completed step
  • result: The result returned by the step
runCompletedfunction#

Called when the entire workflow run finishes.

Parameters:

  • context: The workflow context
  • result: The final result of the workflow

Debug Events#

onErrorfunction#

Called when an error occurs.

Parameters:

  • workflowRunId: The workflow run ID (optional)
  • error: The error object
onWarningfunction#

Called when a warning is logged.

Parameters:

  • workflowRunId: The workflow run ID (optional)
  • warning: The warning message
onInfofunction#

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.