{"id":17252,"library":"http-assert","title":"HTTP Assertions","description":"http-assert is a Node.js module that provides assertion functions designed specifically for HTTP contexts, throwing `HttpError` instances from the widely used `http-errors` package upon assertion failure. It closely mimics the API of Node.js's native `assert` module but extends it by allowing developers to specify an HTTP status code, message, and additional properties for the error object. The current stable version is 1.5.0, with its latest release in 2020. This package maintains a very stable, albeit infrequent, release cadence, often updating to align with new major versions of its core dependency, `http-errors`. Its primary differentiator is the seamless integration of HTTP error status codes into standard assertion patterns, making it particularly well-suited for web frameworks like Koa, where it offers functionality akin to `ctx.throw()` but with a conditional, guard-like behavior.","status":"active","version":"1.5.0","language":"javascript","source_language":"en","source_url":"https://github.com/jshttp/http-assert","tags":["javascript","assert","http"],"install":[{"cmd":"npm install http-assert","lang":"bash","label":"npm"},{"cmd":"yarn add http-assert","lang":"bash","label":"yarn"},{"cmd":"pnpm add http-assert","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core dependency for generating HTTP-specific error objects.","package":"http-errors","optional":false},{"reason":"Used internally for deep equality comparisons in `assert.deepEqual` and `assert.notDeepEqual`.","package":"deep-equal","optional":false}],"imports":[{"note":"The package primarily uses CommonJS `module.exports` as a function. In ESM, it's typically imported as a default export, not a named export. Direct named import `import { assert }` will likely result in a `TypeError`.","wrong":"import { assert } from 'http-assert';","symbol":"assert","correct":"import assert from 'http-assert';"},{"note":"While CommonJS `require` is the original usage, modern Node.js environments often use ESM. This example shows ESM usage of a nested assertion method.","wrong":"const assert = require('http-assert');\nassert.strictEqual(a, b, 400, 'Bad Request');","symbol":"assert.strictEqual","correct":"import assert from 'http-assert';\nassert.strictEqual(a, b, 400, 'Bad Request');"},{"note":"`HttpError` is thrown by `http-assert` but is not directly exported *from* `http-assert`. It originates from the underlying `http-errors` package. To import `HttpError` directly for `instanceof` checks, import it from `http-errors`.","wrong":"import { HttpError } from 'http-assert';","symbol":"HttpError","correct":"import createError from 'http-errors';\n// Or if using http-assert:\ntry { assert(false, 400, 'Invalid'); } catch (err) { /* err is an instance of HttpError */ }"}],"quickstart":{"code":"import assert from 'http-assert';\nimport createError from 'http-errors';\n\nconst user = { id: 123, role: 'admin' };\nconst requestedUserId = '123';\nconst requiredRole = 'admin';\n\nfunction processRequest(data) {\n  try {\n    // Assert that 'data' exists\n    assert(data, 400, 'Request body is required');\n\n    // Assert strict equality for user IDs\n    assert.strictEqual(user.id.toString(), requestedUserId, 403, 'User ID mismatch');\n\n    // Assert user role\n    assert(user.role === requiredRole, 401, 'Unauthorized: Insufficient permissions');\n\n    // If all assertions pass, continue processing\n    console.log('Request processed successfully!');\n    return { status: 200, message: 'Success' };\n  } catch (err) {\n    if (createError.isHttpError(err)) {\n      console.error(`HTTP Error ${err.status}: ${err.message}`);\n      return { status: err.status, message: err.message, expose: err.expose };\n    } else {\n      console.error(`Unexpected error: ${err.message}`);\n      return { status: 500, message: 'Internal Server Error' };\n    }\n  }\n}\n\n// Example usage:\nprocessRequest({ someData: 'value' });\nprocessRequest(null);\nprocessRequest({ invalidUser: true }); // Will fail strictEqual if 'user.id' doesn't match\n","lang":"javascript","description":"This example demonstrates how to use `http-assert` for various checks in a request processing function, catching and handling the `HttpError` instances it throws, and distinguishing them from other errors."},"warnings":[{"fix":"Use `assert.strictEqual(a, b, status, message)` for strict equality comparisons to avoid type coercion issues. For objects, consider if `deepStrictEqual` from Node's native assert or another utility is more appropriate if `http-assert`'s deepEqual (which uses `==`) is too loose.","message":"The `assert.equal` and `assert.deepEqual` methods use the Abstract Equality Comparison (`==`), which performs type coercion. This can lead to unexpected results for developers accustomed to strict equality (`===`) in JavaScript. For strict checks, always use `assert.strictEqual` or `assert.notStrictEqual`.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure that the `status` argument passed to `http-assert` functions is always a valid HTTP error status code (4xx or 5xx). For successful conditions, do not use `http-assert`; instead, proceed with normal execution flow.","message":"The underlying `http-errors` package, which `http-assert` depends on, deprecated the use of non-error status codes (e.g., 2xx, 3xx) in version `1.6.1`. While `http-assert` may still accept them, using a status code outside the 4xx or 5xx range for assertions is strongly discouraged and may lead to unexpected behavior or future breakage.","severity":"deprecated","affected_versions":">=1.3.0"},{"fix":"For ES Modules, use `import assert from 'http-assert';` to import the module's default export. The assertion methods (e.g., `strictEqual`) are then available as properties of the `assert` object (e.g., `assert.strictEqual`).","message":"When migrating from CommonJS (`require`) to ES Modules (`import`), attempting to use `import { assert } from 'http-assert';` will result in a `TypeError` because `http-assert` exports a default function/object, not named exports. This is a common pattern for older CommonJS modules.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Change the import statement to `import assert from 'http-assert';` to correctly import the default export.","cause":"Attempting to use `import { assert } from 'http-assert'` in an ES module environment, where `http-assert` provides a default export.","error":"TypeError: assert is not a function"},{"fix":"Ensure the status argument is a numeric HTTP status code, typically between 400 and 599. Example: `assert(condition, 400, 'Bad Request');`","cause":"The `status` argument passed to an `http-assert` function was not a valid number, or was missing when a status code was expected.","error":"Error: 'status' must be a number"}],"ecosystem":"npm","meta_description":null}