HTTP Assertions
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.
Common errors
-
TypeError: assert is not a function
cause Attempting to use `import { assert } from 'http-assert'` in an ES module environment, where `http-assert` provides a default export.fixChange the import statement to `import assert from 'http-assert';` to correctly import the default export. -
Error: 'status' must be a number
cause The `status` argument passed to an `http-assert` function was not a valid number, or was missing when a status code was expected.fixEnsure the status argument is a numeric HTTP status code, typically between 400 and 599. Example: `assert(condition, 400, 'Bad Request');`
Warnings
- gotcha 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`.
- deprecated 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.
- gotcha 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.
Install
-
npm install http-assert -
yarn add http-assert -
pnpm add http-assert
Imports
- assert
import { assert } from 'http-assert';import assert from 'http-assert';
- assert.strictEqual
const assert = require('http-assert'); assert.strictEqual(a, b, 400, 'Bad Request');import assert from 'http-assert'; assert.strictEqual(a, b, 400, 'Bad Request');
- HttpError
import { HttpError } from 'http-assert';import createError from 'http-errors'; // Or if using http-assert: try { assert(false, 400, 'Invalid'); } catch (err) { /* err is an instance of HttpError */ }
Quickstart
import assert from 'http-assert';
import createError from 'http-errors';
const user = { id: 123, role: 'admin' };
const requestedUserId = '123';
const requiredRole = 'admin';
function processRequest(data) {
try {
// Assert that 'data' exists
assert(data, 400, 'Request body is required');
// Assert strict equality for user IDs
assert.strictEqual(user.id.toString(), requestedUserId, 403, 'User ID mismatch');
// Assert user role
assert(user.role === requiredRole, 401, 'Unauthorized: Insufficient permissions');
// If all assertions pass, continue processing
console.log('Request processed successfully!');
return { status: 200, message: 'Success' };
} catch (err) {
if (createError.isHttpError(err)) {
console.error(`HTTP Error ${err.status}: ${err.message}`);
return { status: err.status, message: err.message, expose: err.expose };
} else {
console.error(`Unexpected error: ${err.message}`);
return { status: 500, message: 'Internal Server Error' };
}
}
}
// Example usage:
processRequest({ someData: 'value' });
processRequest(null);
processRequest({ invalidUser: true }); // Will fail strictEqual if 'user.id' doesn't match