HTTP Assertions

1.5.0 · active · verified Wed Apr 22

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

Warnings

Install

Imports

Quickstart

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.

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

view raw JSON →