HTTP Errors Utility
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.
Common errors
-
TypeError: createError is not a function
cause Attempting to use `new createError()` when `createError` is the default factory function, or incorrectly importing `createError` as a named export in ESM.fixIf `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
cause 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.fixEnsure 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
cause 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.fixSwitch 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.
Warnings
- breaking Version 2.0.0 and above require Node.js >= 10. Users on older Node.js versions must remain on `http-errors@1.x`.
- gotcha The `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.
- gotcha When 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.
- gotcha The 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.
Install
-
npm install http-errors -
yarn add http-errors -
pnpm add http-errors
Imports
- createError
const createError = require('http-errors').createError;import createError from 'http-errors';
- NotFound (and other specific HTTP error constructors)
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 importimport { NotFound } from 'http-errors'; const err = new NotFound('Resource not found'); - isHttpError
import isHttpError from 'http-errors/isHttpError'; // Incorrect subpath import
import { isHttpError } from 'http-errors';
Quickstart
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`);
});