http-errors is a utility library for Node.js environments that simplifies the creation of standardized HTTP error objects, making it easier to integrate consistent error handling into web frameworks like Express, Koa, and Connect. The current stable version, 2.0.1, supports Node.js versions 10 and above and offers both CommonJS and ES module exports. The package maintains a stable release cadence with updates focused on maintenance and minor improvements. It provides a declarative API to generate HTTP errors with appropriate status codes, messages, and optional properties such as `expose` (for client visibility) and `headers`. Key differentiators include its simple factory function (`createError`) and direct constructors for common HTTP status codes (e.g., `createError.NotFound`), abstracting the complexity of managing HTTP-specific error properties.
npm install http-errorsVerified import paths — ran on the pinned version, not inferred.
Demonstrates creating and handling HTTP errors in an Express application, including authentication-related 401s and 404 Not Found errors, using both the factory function and specific error constructors.
Upgrade Node.js to version 10 or higher, or explicitly install `http-errors@1.x` if tied to older Node.js versions.
Always consider the `expose` property when creating errors, especially for 5xx server errors. Explicitly set `expose: true` for 5xx errors only when the message is safe for public consumption and debugging, or `expose: false` for 4xx errors if the message contains sensitive details.
Use `import createError from 'http-errors';` for the default factory and `import { NotFound, isHttpError } from 'http-errors';` for named exports. Avoid `import { createError } from 'http-errors'` as it is incorrect for the default export.Prefer using the `err.status` property when checking the HTTP status code of an `http-errors` object for consistency and clarity.
If `createError` is the factory function, call it directly: `createError(404, 'Message')`. If using ESM, ensure it's imported as a default: `import createError from 'http-errors';`.
Ensure you are using the `new` keyword when instantiating specific error constructors: `new NotFound('Message')`. For CommonJS, it would be `new createError.NotFound('Message')`.Switch to ESM import syntax: `import createError from 'http-errors';` and `import { NotFound } from 'http-errors';`. If maintaining CJS, ensure your project is not configured as an ES module or use dynamic `import()` within CJS.