NODEJS Contents

Async Errors in Express (the safe pattern)

Async errors are the most common Express footgun; production apps must ensure promise rejections always reach the error handler.

On this page

The Async Error Problem

Express was designed in a callback era. If an async handler throws or rejects and the error is not forwarded, you may get unhandled rejections or hung requests.

Safe Wrapper Pattern

Wrap async handlers so any rejection is forwarded to next(). This keeps error handling centralized and prevents silent failures.

import type { Request, Response, NextFunction, RequestHandler } from 'express';

export const asyncHandler = (fn: (req: Request, res: Response, next: NextFunction) => Promise): RequestHandler =>
  (req, res, next) => { void fn(req, res, next).catch(next); };

Why This Matters

In production, one unhandled promise rejection can crash the process depending on runtime settings. Even if it does not crash, it can create inconsistent responses and broken observability.