Async Express/Connect Middleware Wrapper

1.2.1 · maintenance · verified Wed Apr 22

async-middleware is a utility package designed to simplify error handling for asynchronous middleware functions within web frameworks like Express and Connect. It wraps an `async` or Promise-returning function, automatically catching rejected Promises and forwarding the error to the `next(err)` callback, preventing uncaught Promise rejections from crashing the application. The package is currently at version 1.2.1 and appears to be in a maintenance state, with the last release being in 2017 focusing on minor fixes and dependency cleanups rather than new features. Its key differentiator is its singular focus on robust async error piping for traditional middleware stacks, providing a lightweight alternative to more comprehensive async libraries. It ships with TypeScript types, enhancing developer experience for type-safe applications.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates wrapping both resolving and rejecting asynchronous Express middleware functions, showcasing how 'async-middleware' automatically pipes Promise rejections to the Express error handler.

import express from 'express';
import { wrap } from 'async-middleware';

const app = express();

// Basic asynchronous middleware that resolves after a delay
app.get('/success', wrap(async (req, res) => {
  await new Promise(resolve => setTimeout(resolve, 100));
  res.send('Operation successful!');
}));

// Asynchronous middleware that rejects with an error
app.get('/fail', wrap(async (req, res) => {
  await new Promise((_, reject) => setTimeout(() => reject(new Error('Something went wrong!')), 50));
  // This line will not be reached
  res.status(200).send('Should not see this');
}));

// Error handling middleware (must be defined last)
app.use((err: Error, req: express.Request, res: express.Response, next: express.NextFunction) => {
  console.error('Caught by error handler:', err.message);
  res.status(500).send(`Error: ${err.message}`);
});

const PORT = process.env.PORT ?? 3000;
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
  console.log('Try visiting http://localhost:3000/success and http://localhost:3000/fail');
});

view raw JSON →