npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@saga-bus/express

v0.2.1

Published

Express.js integration for saga-bus

Readme

@saga-bus/express

Express.js integration for saga-bus with middleware, health checks, and graceful shutdown.

Installation

npm install @saga-bus/express express
# or
pnpm add @saga-bus/express express

Features

  • Bus Middleware: Attaches bus instance to req.bus
  • Correlation ID: Extract or generate correlation IDs from headers
  • Health Checks: Ready-to-use health and readiness endpoints
  • Error Handler: Saga-specific error handling middleware
  • Graceful Shutdown: Clean shutdown with bus draining

Quick Start

import express from "express";
import { createBus } from "@saga-bus/core";
import {
  sagaBusMiddleware,
  sagaErrorHandler,
  createHealthRouter,
  setupGracefulShutdown,
} from "@saga-bus/express";

const bus = createBus({ /* config */ });
await bus.start();

const app = express();

// Attach bus to requests
app.use(sagaBusMiddleware({ bus }));

// Health check endpoint
app.use(createHealthRouter({ bus }));

// Your routes
app.post("/orders", async (req, res) => {
  await req.bus.publish({
    type: "CreateOrder",
    payload: req.body,
  });
  res.json({ correlationId: req.correlationId });
});

// Error handler (must be last)
app.use(sagaErrorHandler());

const server = app.listen(3000);

// Graceful shutdown
setupGracefulShutdown(server, { bus });

API Reference

sagaBusMiddleware(options)

Creates middleware that attaches the bus instance to requests.

interface SagaBusExpressOptions {
  /** The bus instance to attach */
  bus: Bus;

  /** Header name for correlation ID (default: "x-correlation-id") */
  correlationIdHeader?: string;

  /** Whether to generate correlation ID if not present (default: true) */
  generateCorrelationId?: boolean;

  /** Custom correlation ID generator */
  correlationIdGenerator?: () => string;
}

Example:

app.use(sagaBusMiddleware({
  bus,
  correlationIdHeader: "x-request-id",
  correlationIdGenerator: () => `req-${Date.now()}`,
}));

sagaErrorHandler()

Error handler middleware for saga-related errors.

  • SagaTimeoutError: Returns 408 Request Timeout
  • ConcurrencyError: Returns 409 Conflict
app.use(sagaErrorHandler());

createHealthRouter(options)

Creates a health check router.

interface HealthCheckOptions {
  /** The bus instance to check */
  bus: Bus;

  /** Path for health endpoint (default: "/health") */
  path?: string;

  /** Additional health checks */
  checks?: Array<{
    name: string;
    check: () => Promise<boolean>;
  }>;
}

Example:

app.use(createHealthRouter({
  bus,
  path: "/health",
  checks: [
    {
      name: "database",
      check: async () => {
        await pool.query("SELECT 1");
        return true;
      },
    },
  ],
}));

Response format:

{
  "status": "healthy",
  "timestamp": "2024-01-01T00:00:00.000Z",
  "checks": {
    "bus": { "status": "pass" },
    "database": { "status": "pass" }
  }
}

createReadinessRouter(options)

Same as createHealthRouter but defaults to /ready path.

app.use(createReadinessRouter({ bus }));

setupGracefulShutdown(server, options)

Sets up graceful shutdown with bus draining.

interface GracefulShutdownOptions {
  /** The bus instance to drain */
  bus: Bus;

  /** Timeout for graceful shutdown in ms (default: 30000) */
  timeoutMs?: number;

  /** Callback before shutdown starts */
  onShutdownStart?: () => void | Promise<void>;

  /** Callback after shutdown completes */
  onShutdownComplete?: () => void | Promise<void>;
}

Example:

setupGracefulShutdown(server, {
  bus,
  timeoutMs: 60000,
  onShutdownStart: async () => {
    console.log("Stopping background jobs...");
  },
  onShutdownComplete: async () => {
    await pool.end();
    console.log("Cleanup complete");
  },
});

TypeScript Support

The package extends Express types to add bus and correlationId to requests:

// In your route handlers
app.post("/orders", async (req, res) => {
  // req.bus is typed as Bus
  await req.bus.publish(message);

  // req.correlationId is typed as string | undefined
  console.log(`Processing ${req.correlationId}`);
});

Example: Complete Application

import express from "express";
import { createBus, InMemoryTransport, InMemorySagaStore } from "@saga-bus/core";
import {
  sagaBusMiddleware,
  sagaErrorHandler,
  createHealthRouter,
  createReadinessRouter,
  setupGracefulShutdown,
} from "@saga-bus/express";

// Create bus
const bus = createBus({
  transport: new InMemoryTransport(),
  store: new InMemorySagaStore(),
});

await bus.start();

// Create Express app
const app = express();
app.use(express.json());

// Saga bus middleware
app.use(sagaBusMiddleware({ bus }));

// Health endpoints
app.use(createHealthRouter({ bus }));
app.use(createReadinessRouter({ bus }));

// Routes
app.post("/messages", async (req, res) => {
  await req.bus.publish({
    type: req.body.type,
    payload: req.body.payload,
  });
  res.json({ success: true, correlationId: req.correlationId });
});

// Error handler (must be last middleware)
app.use(sagaErrorHandler());

// Start server
const server = app.listen(3000, () => {
  console.log("Server running on port 3000");
});

// Graceful shutdown
setupGracefulShutdown(server, {
  bus,
  timeoutMs: 30000,
});

License

MIT