Async middleware wrapper helps handle errors in async Express middleware easily. It avoids repeating try-catch blocks.
Async middleware wrapper in Express
const asyncWrapper = (fn) => (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};This is a higher-order function that takes an async function fn and returns a new middleware function.
It runs fn and catches any errors, passing them to next() for Express error handling.
const asyncWrapper = (fn) => (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};app.get('/data', asyncWrapper(async (req, res) => { const data = await getDataFromDb(); res.json(data); }));
app.post('/user', asyncWrapper(async (req, res) => { const user = await createUser(req.body); res.status(201).json(user); }));
This Express app uses an async middleware wrapper to handle errors in an async route. The route /hello returns JSON after a delay. Errors are caught and sent as JSON error responses.
import express from 'express'; const app = express(); app.use(express.json()); const asyncWrapper = (fn) => (req, res, next) => { Promise.resolve(fn(req, res, next)).catch(next); }; // Simulated async function const getData = async () => { return new Promise((resolve) => setTimeout(() => resolve({ message: 'Hello World' }), 100)); }; app.get('/hello', asyncWrapper(async (req, res) => { const data = await getData(); res.json(data); })); // Error handler middleware app.use((err, req, res, next) => { res.status(500).json({ error: err.message }); }); app.listen(3000, () => console.log('Server running on port 3000'));
Always use the async wrapper on async middleware to avoid unhandled promise rejections.
The wrapper passes errors to Express's built-in error handler or your custom error middleware.
This pattern keeps your code clean and easier to read.
Async middleware wrapper catches errors from async functions automatically.
It helps avoid repetitive try-catch blocks in Express middleware.
Use it to keep async route handlers clean and error-safe.