{"id":16064,"library":"http-errors","title":"HTTP Errors Utility","description":"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.","status":"active","version":"2.0.1","language":"javascript","source_language":"en","source_url":"https://github.com/jshttp/http-errors","tags":["javascript","http","error"],"install":[{"cmd":"npm install http-errors","lang":"bash","label":"npm"},{"cmd":"yarn add http-errors","lang":"bash","label":"yarn"},{"cmd":"pnpm add http-errors","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Provides deprecation messaging for Node.js APIs.","package":"depd","optional":false},{"reason":"Utility for JavaScript inheritance, used internally for error constructors.","package":"inherits","optional":false},{"reason":"Reliably sets the prototype of an object, used for extending error objects.","package":"setprototypeof","optional":false},{"reason":"Provides a comprehensive list of HTTP status codes and their messages.","package":"statuses","optional":false},{"reason":"Converts strings to valid JavaScript identifiers, used for error names.","package":"toidentifier","optional":false}],"imports":[{"note":"The primary factory function is the default export in ESM. For CJS, `require('http-errors')` directly returns the factory function.","wrong":"const createError = require('http-errors').createError;","symbol":"createError","correct":"import createError from 'http-errors';"},{"note":"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()`.","wrong":"import NotFound from 'http-errors/lib/not-found'; // Incorrect subpath import\nconst err = createError.NotFound('Resource not found'); // This is a function call, not a constructor with 'new' in ESM named import","symbol":"NotFound (and other specific HTTP error constructors)","correct":"import { NotFound } from 'http-errors';\nconst err = new NotFound('Resource not found');"},{"note":"The `isHttpError` type guard is a named export in ESM and a property of the main `createError` object in CJS: `require('http-errors').isHttpError`.","wrong":"import isHttpError from 'http-errors/isHttpError'; // Incorrect subpath import","symbol":"isHttpError","correct":"import { isHttpError } from 'http-errors';"}],"quickstart":{"code":"import createError, { NotFound } from 'http-errors';\nimport express from 'express';\n\nconst app = express();\n\n// Middleware to simulate authentication\napp.use((req, res, next) => {\n  // For demonstration, let's assume a user is NOT logged in by default\n  req.user = null; // or { id: 1, name: 'Test User' };\n  next();\n});\n\napp.get('/', (req, res, next) => {\n  res.send('Welcome! Try navigating to /protected or /non-existent');\n});\n\napp.get('/protected', (req, res, next) => {\n  if (!req.user) {\n    // Create a 401 Unauthorized error\n    return next(createError(401, 'Please login to view this page.'));\n  }\n  res.send(`Hello, ${req.user.name}! This is a protected page.`);\n});\n\napp.get('/non-existent', (req, res, next) => {\n  // Create a 404 Not Found error using a specific constructor\n  next(new NotFound('The requested resource does not exist.'));\n});\n\n// Catch-all for 404s that haven't been caught by other routes\napp.use((req, res, next) => {\n  next(new NotFound(`Cannot ${req.method} ${req.originalUrl}`));\n});\n\n// Error handling middleware\napp.use((err, req, res, next) => {\n  res.status(err.status || 500);\n  res.json({\n    status: err.status,\n    message: err.expose ? err.message : 'Internal Server Error'\n  });\n});\n\nconst PORT = process.env.PORT || 3000;\napp.listen(PORT, () => {\n  console.log(`Server listening on port ${PORT}`);\n  console.log(`Try: http://localhost:${PORT}/`);\n  console.log(`Try: http://localhost:${PORT}/protected`);\n  console.log(`Try: http://localhost:${PORT}/non-existent`);\n});\n","lang":"typescript","description":"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."},"warnings":[{"fix":"Upgrade Node.js to version 10 or higher, or explicitly install `http-errors@1.x` if tied to older Node.js versions.","message":"Version 2.0.0 and above require Node.js >= 10. Users on older Node.js versions must remain on `http-errors@1.x`.","severity":"breaking","affected_versions":">=2.0.0"},{"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.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"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.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"Prefer using the `err.status` property when checking the HTTP status code of an `http-errors` object for consistency and clarity.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"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';`.","cause":"Attempting to use `new createError()` when `createError` is the default factory function, or incorrectly importing `createError` as a named export in ESM.","error":"TypeError: createError is not a function"},{"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')`.","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.","error":"TypeError: (0 , http_errors__WEBPACK_IMPORTED_MODULE_0__.NotFound) is not a constructor"},{"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.","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.","error":"Error [ERR_REQUIRE_ESM]: require() of ES Module ... not supported"}],"ecosystem":"npm"}