Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslnode 18–226 runs
build_error
glibcnode 18–226 runs
build_error
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
asyncMiddleware
✓ import asyncMiddleware from 'middleware-async';
✗ const asyncMiddleware = require('middleware-async').asyncMiddleware;
The package's primary export is a function. For CommonJS, `require('middleware-async')` directly returns the function. For ESM, it's a default import.
Demonstrates wrapping an asynchronous Express middleware with `asyncMiddleware` to catch promise rejections and forward them to Express's error handler, preventing application crashes.
import express from 'express';
import asyncMiddleware from 'middleware-async';
const app = express();
// A simulated asynchronous operation
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const success = Math.random() > 0.5;
if (success) {
resolve({ message: 'Data fetched successfully!' });
} else {
reject(new Error('Failed to fetch data.'));
}
}, 500);
});
};
// Define an async middleware that uses fetchData
const myAsyncMiddleware = async (req, res, next) => {
console.log('Attempting to fetch data...');
const data = await fetchData(); // This might reject
req.fetchedData = data;
next();
};
// Use the asyncMiddleware wrapper
app.get('/data', asyncMiddleware(myAsyncMiddleware), (req, res) => {
res.json({ status: 'Success', data: req.fetchedData });
});
// Error handling middleware (must be defined last)
app.use((err, req, res, next) => {
console.error('An error occurred:', err.message);
res.status(500).json({ status: 'Error', message: 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/data multiple times to see success/failure.');
});
Debug
Known issues
breakingExpress 5.x introduces native support for async route handlers and middleware, automatically catching unhandled promise rejections and passing them to `next(err)`. This package becomes largely redundant in Express 5.x and newer versions, potentially causing unnecessary overhead or conflicts if used alongside native handling.fixFor new projects or when upgrading to Express 5.x+, consider removing `middleware-async` and writing async middleware directly. Ensure a global error handling middleware is in place for all errors. Example: `app.get('/', async (req, res) => { throw new Error('Broken'); });` affects: >=5.0.0 (for Express)
gotchaWithout a wrapper like `middleware-async` (or Express 5.x's native support), a rejected Promise in an `async` Express middleware will result in an `UnhandledPromiseRejectionWarning` and can crash your Node.js process, as Express 4.x does not automatically catch async errors.fixAlways wrap async middleware functions using `asyncMiddleware` or explicitly use `try...catch` blocks or `.catch(next)` within each async middleware for Express versions older than 5.x.
affects: <5.0.0 (for Express)
deprecatedThe package has not seen updates since 2017 (version 1.4.0). While functional for its intended purpose with older Express versions, it lacks modern maintenance, features, or explicit ESM support. Consider `express-async-handler` for a more recently maintained alternative for Express 4.x, or upgrade to Express 5.x for native support.fixFor new projects, prefer native async error handling in Express 5.x. For older projects, evaluate `express-async-handler` (`npm i express-async-handler`) as a potentially more robust and maintained alternative if `middleware-async` encounters issues.
affects: *
Errors
Common errors & fixes
UnhandledPromiseRejectionWarning: A promise was rejected with a non-error value.
An asynchronous middleware function returned a rejected Promise, but the rejection was not caught by Express or a wrapper, leading to an unhandled rejection at the process level. This is common in Express 4.x without a wrapper.
fixEnsure all async Express middleware functions are wrapped with `asyncMiddleware` (e.g., `app.get('/route', asyncMiddleware(myAsyncFunc), ...)`) or manually include `try...catch` blocks or `.catch(next)` within your async functions. TypeError: app.use() requires a middleware function but got a Object
This typically occurs when `require('middleware-async')` is used in a way that attempts to access a named export (e.g., `.asyncMiddleware`) when the package's main export is the function itself, or if an ESM default import is used incorrectly in CommonJS.
fixFor CommonJS, import the module directly as a function: `const asyncMiddleware = require('middleware-async');`. For ESM, use `import asyncMiddleware from 'middleware-async';`. Audit
Dependencies
No dependency data recorded yet.