Wrapper for async Express route handlers
Quick Answer
`asyncHandler` wraps an async Express route so any rejected promise is automatically forwarded to `next(err)` — no try/catch boilerplate in every route.
1import { Request, Response, NextFunction } from 'express';
2
3type AsyncHandler = (
4 req: Request,
5 res: Response,
6 next: NextFunction
7) => Promise<any>;
8
9const asyncHandler = (fn: AsyncHandler) => {
10 return (req: Request, res: Response, next: NextFunction) => {
11 Promise.resolve(fn(req, res, next)).catch(next);
12 };
13};
14
15export default asyncHandler;Express does not natively catch errors thrown in async route handlers — unhandled promise rejections will crash the process or hang the request. asyncHandler wraps an async function and passes any rejection to Express's next(err) so your error middleware handles it cleanly.
No — Express 5 natively catches rejected promises from async route handlers. This pattern is only required for Express 4.
This free typescript code snippet for async route handler is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this intermediate-level example will help you implement async route handler quickly and correctly.
All snippets in the Snippetly library follow typescript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses typescript.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.