Throwback Async Middleware Composer

4.1.0 · active · verified Wed Apr 22

Throwback is a lightweight JavaScript/TypeScript library that implements a simple asynchronous middleware pattern, designed to compose promise-returning functions. It is currently in its stable version 4.1.0 and maintains an active release cadence, frequently introducing breaking changes in major versions to refine its API. Key differentiators include its strict focus on a single `ctx` argument for improved TypeScript inference (since v3.0.0), its reliance solely on native Promises (since v2.0.0), and its inspiration from Koa's middleware composition, aiming for a minimalistic yet powerful approach for processing pipelines. It is commonly used in server-side HTTP applications (e.g., Servie) and client-side request libraries (e.g., Popsicle), providing development-time debugging aids that are automatically excluded from production builds.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to compose asynchronous middleware functions and execute a stack with a context object and a final callback, showing the order of execution.

import { compose } from 'throwback';

const middlewareStack = [
  async function firstMiddleware(ctx, next) {
    console.log('1: Before next()');
    // 'next()' calls the next middleware in the stack or the final callback.
    await next();
    console.log('4: After next()');
  },
  async function secondMiddleware(ctx, next) {
    console.log('2: Calling next()');
    // You can optionally pass a new context to 'next()' which will replace it
    // for subsequent middleware in the stack and the final callback (since v3).
    // This is useful for request retries or modifying the context downstream.
    await next();
    console.log('3: Returning from next()');
  }
];

const composedApp = compose(middlewareStack);

// The composed function takes a context object and an optional final callback.
// The final callback runs at the end of the middleware stack, before the
// execution bubbles back up through the middleware.
composedApp({}, function finalCallback(ctx) {
  console.log('5: Final callback executed. Context:', ctx);
  ctx.status = 200;
});

/* Expected output:
1: Before next()
2: Calling next()
5: Final callback executed. Context: { status: 200 }
3: Returning from next()
4: After next()
*/

view raw JSON →