Registry / http-networking / http-errors

http-errors

JSON →
library2.0.1jsnpmunverified

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-errors
INSTALL
IMPORT
SIG · HTTP-ERRORS
H
http-errors
http-networkingjavascriptv2.0.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

createError
import createError from 'http-errors';
const createError = require('http-errors').createError;
The primary factory function is the default export in ESM. For CJS, `require('http-errors')` directly returns the factory function.
NotFound (and other specific HTTP error constructors)
import { NotFound } from 'http-errors'; const err = new NotFound('Resource not found');
import NotFound from 'http-errors/lib/not-found'; // Incorrect subpath import const err = createError.NotFound('Resource not found'); // This is a function call, not a constructor with 'new' in ESM named import
Specific HTTP error constructors (e.g., BadRequest, Unauthorized, NotFound) are exported as named exports in ESM. In CJS, they are properties of the `createError` object and should be instantiated with `new`, e.g., `new createError.NotFound()`.
isHttpError
import { isHttpError } from 'http-errors';
import isHttpError from 'http-errors/isHttpError'; // Incorrect subpath import
The `isHttpError` type guard is a named export in ESM and a property of the main `createError` object in CJS: `require('http-errors').isHttpError`.

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.

import createError, { NotFound } from 'http-errors'; import express from 'express'; const app = express(); // Middleware to simulate authentication app.use((req, res, next) => { // For demonstration, let's assume a user is NOT logged in by default req.user = null; // or { id: 1, name: 'Test User' }; next(); }); app.get('/', (req, res, next) => { res.send('Welcome! Try navigating to /protected or /non-existent'); }); app.get('/protected', (req, res, next) => { if (!req.user) { // Create a 401 Unauthorized error return next(createError(401, 'Please login to view this page.')); } res.send(`Hello, ${req.user.name}! This is a protected page.`); }); app.get('/non-existent', (req, res, next) => { // Create a 404 Not Found error using a specific constructor next(new NotFound('The requested resource does not exist.')); }); // Catch-all for 404s that haven't been caught by other routes app.use((req, res, next) => { next(new NotFound(`Cannot ${req.method} ${req.originalUrl}`)); }); // Error handling middleware app.use((err, req, res, next) => { res.status(err.status || 500); res.json({ status: err.status, message: err.expose ? err.message : 'Internal Server Error' }); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server listening on port ${PORT}`); console.log(`Try: http://localhost:${PORT}/`); console.log(`Try: http://localhost:${PORT}/protected`); console.log(`Try: http://localhost:${PORT}/non-existent`); });
Debug
Known issues
breakingVersion 2.0.0 and above require Node.js >= 10. Users on older Node.js versions must remain on `http-errors@1.x`.
fix
Upgrade Node.js to version 10 or higher, or explicitly install `http-errors@1.x` if tied to older Node.js versions.
affects: >=2.0.0
gotchaThe `expose` property dictates whether the error message is sent to the client. By default, messages for 5xx errors are not exposed (`expose: false`) to prevent information leakage. For client errors (4xx), messages are exposed (`expose: true`). Mismanaging this can lead to sensitive internal details being leaked or helpful client-side error messages being suppressed.
fix
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.
affects: >=1.0.0
gotchaWhen using ESM `import` statements, ensure correct import syntax. The main `createError` function is a default export, while specific error constructors (e.g., `NotFound`, `BadRequest`) and `isHttpError` are named exports. Incorrectly mixing default and named import syntax can lead to runtime errors.
fix
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.
affects: >=2.0.0
gotchaThe library internally uses both `status` and `statusCode` properties on error objects for compatibility. While `status` is the primary property for HTTP status, be aware that `statusCode` will mirror its value. Relying on `statusCode` directly when `status` is intended can be confusing if the values diverge in future versions, though currently they are synchronized.
fix
Prefer using the `err.status` property when checking the HTTP status code of an `http-errors` object for consistency and clarity.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: createError is not a function
Attempting to use `new createError()` when `createError` is the default factory function, or incorrectly importing `createError` as a named export in ESM.
fix
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';`.
TypeError: (0 , http_errors__WEBPACK_IMPORTED_MODULE_0__.NotFound) is not a constructor
Attempting to instantiate a specific HTTP error constructor (e.g., `NotFound`, `BadRequest`) as a function call instead of using `new` with the constructor, typically in a transpiled environment or incorrect ESM usage.
fix
Ensure you are using the `new` keyword when instantiating specific error constructors: `new NotFound('Message')`. For CommonJS, it would be `new createError.NotFound('Message')`.
Error [ERR_REQUIRE_ESM]: require() of ES Module ... not supported
Attempting to use `require()` to import `http-errors` in a Node.js project configured as an ES Module (e.g., `"type": "module"` in `package.json`), where `http-errors` is treated as an ESM module.
fix
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.
Upgrade
Version history
2.0.1latest on npm
Audit
Dependencies
depdrequiredProvides deprecation messaging for Node.js APIs.
inheritsrequiredUtility for JavaScript inheritance, used internally for error constructors.
setprototypeofrequiredReliably sets the prototype of an object, used for extending error objects.
statusesrequiredProvides a comprehensive list of HTTP status codes and their messages.
toidentifierrequiredConverts strings to valid JavaScript identifiers, used for error names.
Agent activity
4 hits · last 30 days
node
4
Resources