express-async-handler-plus
v1.0.3
Published
A lightweight utility to handle async Express routes and routers with built-in error handling and auto JSON responses.
Maintainers
Readme
express-async-handler-plus
A lightweight utility to handle async Express routes and routers with built-in error handling and auto JSON responses.
✨ Features
- Auto error handling
- Auto JSON responses
- Router-wide wrapping
- Works with both app and Router()
- No external dependencies
- Super tiny and fast (<2KB)
📦 Install
npm install express-async-handler-plus🚀 Usage
import express from "express";
import { asyncHandler, jsonHandler, wrapRouter } from "express-async-handler-plus";
const app = express();
// ✅ Example route with asyncHandler
app.get(
"/hello",
asyncHandler(async (req, res) => {
// Simulate async work
const user = await Promise.resolve({ id: 1, name: "Manu" });
res.json({ success: true, user });
})
);
// ✅ Example route with jsonHandler (auto JSON response)
app.get(
"/auto",
jsonHandler(async () => {
return { msg: "Auto JSON handled!" };
})
);
// ✅ Example wrapped router
const router = express.Router();
router.get(
"/data",
async (req, res) => {
// No need to wrap manually
return { items: [1, 2, 3] };
}
);
app.use("/api", wrapRouter(router));
app.listen(3000, () => console.log("🚀 Server running on http://localhost:3000"));✅ Example Output
GET /hello
{
"success": true,
"user": { "id": 1, "name": "Manu" }
}
GET /auto
{
"success": true,
"data": { "msg": "Auto JSON handled!" }
}
GET /api/data
{
"success": true,
"data": { "items": [1, 2, 3] }
}