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.
npm install http-assertVerified import paths — ran on the pinned version, not inferred.
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.
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.
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.
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`).
Change the import statement to `import assert from 'http-assert';` to correctly import the default export.
Ensure the status argument is a numeric HTTP status code, typically between 400 and 599. Example: `assert(condition, 400, 'Bad Request');`