{"id":17088,"library":"async-middleware","title":"Async Express/Connect Middleware Wrapper","description":"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.","status":"maintenance","version":"1.2.1","language":"javascript","source_language":"en","source_url":"git://github.com/blakeembrey/async-middleware","tags":["javascript","middleware","express","async","promise","handler","typescript"],"install":[{"cmd":"npm install async-middleware","lang":"bash","label":"npm"},{"cmd":"yarn add async-middleware","lang":"bash","label":"yarn"},{"cmd":"pnpm add async-middleware","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"For ESM projects, use named import. This package primarily targets CommonJS but provides ESM compatibility.","wrong":"const wrap = require('async-middleware');","symbol":"wrap","correct":"import { wrap } from 'async-middleware';"},{"note":"CommonJS projects should use destructuring assignment from the `require` call. The 'wrap' function is a named export, not a default export.","wrong":"const wrap = require('async-middleware').default;","symbol":"wrap","correct":"const { wrap } = require('async-middleware');"},{"note":"The package ships with TypeScript types. Use a type import for better tree-shaking and type safety.","symbol":"WrapMiddleware","correct":"import type { WrapMiddleware } from 'async-middleware';"}],"quickstart":{"code":"import express from 'express';\nimport { wrap } from 'async-middleware';\n\nconst app = express();\n\n// Basic asynchronous middleware that resolves after a delay\napp.get('/success', wrap(async (req, res) => {\n  await new Promise(resolve => setTimeout(resolve, 100));\n  res.send('Operation successful!');\n}));\n\n// Asynchronous middleware that rejects with an error\napp.get('/fail', wrap(async (req, res) => {\n  await new Promise((_, reject) => setTimeout(() => reject(new Error('Something went wrong!')), 50));\n  // This line will not be reached\n  res.status(200).send('Should not see this');\n}));\n\n// Error handling middleware (must be defined last)\napp.use((err: Error, req: express.Request, res: express.Response, next: express.NextFunction) => {\n  console.error('Caught by error handler:', err.message);\n  res.status(500).send(`Error: ${err.message}`);\n});\n\nconst PORT = process.env.PORT ?? 3000;\napp.listen(PORT, () => {\n  console.log(`Server running on http://localhost:${PORT}`);\n  console.log('Try visiting http://localhost:3000/success and http://localhost:3000/fail');\n});","lang":"typescript","description":"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."},"warnings":[{"fix":"Ensure your asynchronous middleware functions explicitly return Promises or are `async` functions. If you need to convert a non-Promise value, do so explicitly (e.g., `Promise.resolve(value)`) before returning it.","message":"Prior to v1.1.0, `async-middleware` would use `Promise.resolve` on all return values, potentially converting non-Promise values into Promises. Starting with v1.1.0, it strictly only handles `Promise`-like returns and ignores other values. If your middleware explicitly returned non-Promise values that you expected to be 'resolved' into Promises, this behavior changed.","severity":"breaking","affected_versions":"<1.1.0"},{"fix":"For older environments, ensure a Promise polyfill is globally available before `async-middleware` is initialized (e.g., `require('core-js/es6/promise')` or similar).","message":"Version 1.2.0 dropped the `any-promise` dependency, relying solely on native ES6 Promise types. While this generally improves performance and reduces bundle size, it means environments without native Promise support (e.g., older Node.js or browser versions without polyfills) might require an explicit Promise polyfill if you're using this library.","severity":"gotcha","affected_versions":">=1.2.0"},{"fix":"Ensure `typeRoots` in your `tsconfig.json` includes `node_modules/@types` or simply remove `typeRoots` to allow TypeScript to discover `@types` automatically if you are not using custom type roots.","message":"When using TypeScript, earlier versions might have relied on ambient type declarations. Version 1.2.0 moved type definitions to `@types`, which means your `tsconfig.json` should be configured to include `@types` packages correctly.","severity":"gotcha","affected_versions":">=1.2.0"},{"fix":"Always reject Promises with an `Error` instance (e.g., `Promise.reject(new Error('message'))`) to provide meaningful error information in your error handling middleware.","message":"While `async-middleware` catches rejected Promises, it does not provide any default error transformation. If a Promise rejects with a falsy value (e.g., `null` or `undefined`), v1.1.0 and later will `next()` a custom `Error` instance with a generic message, rather than the falsy value itself. Always reject with actual `Error` objects for clearer debugging.","severity":"gotcha","affected_versions":">=1.1.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Use `const { wrap } = require('async-middleware');` for CommonJS or `import { wrap } from 'async-middleware';` for ESM.","cause":"Attempting to `require('async-middleware')` directly without accessing the named export `wrap`.","error":"TypeError: Cannot read properties of undefined (reading 'wrap')"},{"fix":"Ensure that your Promises consistently reject with `Error` objects. For example, instead of `Promise.reject({ code: 500 })`, use `Promise.reject(new Error('Internal Server Error'))`.","cause":"`async-middleware` caught a rejected Promise where the rejected value was not an `Error` object, and the upstream error handler expects `Error` instances.","error":"Error: next() called with non-Error object: [object Object]"}],"ecosystem":"npm","meta_description":null}