npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

assert-response

v0.2.1

Published

A lightweight utility library for asserting HTTP response conditions and throwing a Response with the appropriate HTTP status code, and optional body and options.

Readme

assert-response

A lightweight utility library for asserting HTTP response conditions and throwing a Response with the appropriate HTTP status code, and optional body and options.

Usage

Ensure a resource exists

If the resource is missing, throw a 404 Not Found response.

import { found } from "assert-response";

function loader() {
  const foo = getFoo(); // Foo | undefined

  // Throws a 404 response if foo is undefined
  found(foo);

  foo; // Type is now Foo
  // Do something with foo
}

Require authentication

If the user is not authenticated, throw a 401 Unauthorized response.

import { authorized } from "assert-response";

function action() {
  const user = getCurrentUser(); // User | null

  // Throws a 401 response if user is null
  authorized(user);

  user; // Type is now User
  // ...
}

Validate a successful operation

If the operation was unsuccessful, throw a 500 Internal Server Error.

import { noError } from "assert-response";

function action() {
  const success = processRequest(); // boolean

  // Throws a 500 response if success is false
  noError(success);
  // Do further actions
}

Validate an unsuccessful operation

If the operation was successful, throw a 200 OK.

import { internalServerError, notOk } from "assert-response";

function action() {
  const [error] = processOtherRequest(); // [string | null]

  // Throws a 200 response if error is null
  notOk(error);
  error; // Type is now string

  console.error(error);

  // Throws a 500 response if error is not null
  internalServerError(error);
}

Validate permissions and resource conflicts before saving

This example ensures:

  • 👋 The user is authenticated (401 Unauthorized).
  • 🔓 The user has permission to update the document (403 Forbidden).
  • ✅ The input is valid (400 Bad Request).
  • 🔍 The document exists (404 Not Found).
  • 🤝 The document has not been modified since the last retrieval (409 Conflict).
  • ⚠️ / 👌 The update is successful (500 Internal Server Error / 204 No Content).
import {
  authorized,
  allowed,
  found,
  match,
  noContent,
  valid,
  internalServerError,
} from "assert-response";

interface Document {
  id: string;
  lastModified: number;
}

async function saveAndContinueEditing(doc?: Document) {
  const user = getCurrentUser();
  // 👋 Throws a 401 response if current user is null
  authorized(user, "Authentication required");
  user; // Type is now User

  // 🔓 Throws a 403 response if not permitted
  allowed(
    user.permissions.includes("update-document"),
    "Permission to update document required"
  );

  // ✅ Throws a 400 response if missing update document
  valid(doc, "Missing document");
  doc; // Type is now Document

  const prevDoc: Document | undefined = await database.find(doc.id);
  // 🔍 Throws a 404 response if the document does not exist
  found(prevDoc, "Document not found");
  prevDoc; // Type is now Document

  // 🤝 Throws a 409 response if the document has been modified since last retrieval
  match(prevDoc.lastModified === doc.lastModified, "Conflict detected");

  const [error] = await database.put(doc);

  // ⚠️ Throws a 500 response if the update failed
  internalServerError(error);

  // 👌 Throws a 204 response if everything successful
  noContent(true);
}

API

Each assertion function checks a condition and throws a Response with the corresponding HTTP status code if the condition is truthy. Negated functions work in reverse: they throw a response when the condition is falsy.

You may also pass an optional body and options parameters for Response as the second and third arguments for the assertion function. These can either be values or functions that return the respective values.

To use these functions:

import { found, ok, redirect, valid } from "assert-response";

// Throws a 200 response if user is truthy, with a dynamic message
ok(
  user,
  () => JSON.stringify({ message: "Welcome back!" }),
  () => ({ headers: { "Content-Type": "application/json" } })
);

// Throws a 302 response with options if redirectURL is set
redirect(redirectURL, undefined, {
  headers: {
    Location: redirectURL!,
  },
});

// Validate user input (Negated function, throws 400 response if condition is falsy)
valid(isValid(input), "Invalid input");

// Ensure item is found (Negated function, throws 404 response if condition is falsy)
found(item, "Item not found");

Assertion Functions

Each function is mapped to an HTTP status code.

Successful Responses (200299)

| Status Code | Function (Aliases) | Negated Function (Aliases) | | ------------------------------------------------------------- | ----------------------------- | -------------------------------------------------------------------- | | 200 | ok (successful) | notOk (failed) | | 201 | created | notCreated (creationFailed) | | 202 | accepted | notAccepted (rejected) | | 203 | nonAuthoritativeInformation | notNonAuthoritativeInformation (authoritativeInformation) | | 204 | noContent | notNoContent (content) | | 205 | resetContent | notResetContent | | 206 | partialContent | notPartialContent (entireContent, fullContent) | | 207 | multiStatus | notMultiStatus (singleStatus) | | 208 | alreadyReported | notAlreadyReported | | 226 | imUsed | notImUsed |

Redirection Responses (300399)

| Status Code | Function (Aliases) | Negated Function (Aliases) | | ------------------------------------------------------------- | ------------------------------------ | ----------------------------------------- | | 300 | multipleChoices | notMultipleChoices | | 301 | movedPermanently | notMovedPermanently | | 302 | temporaryFound (redirect) | notTemporaryFound (noRedirect) | | 303 | seeOther | notSeeOther | | 304 | notModified | modified | | 305 | useProxy (proxy) | notUseProxy | | 307 | temporaryRedirect | notTemporaryRedirect | | 308 | permanentRedirect | notPermanentRedirect |

Client Error Responses (400499)

| Status Code | Function (Aliases) | Negated Function (Aliases) | | ------------------------------------------------------------- | ------------------------------- | ------------------------------------------------------------------------- | | 400 | badRequest (invalid) | goodRequest (valid, correct) | | 401 | unauthorized | authorized (authenticated) | | 402 | paymentRequired | paymentNotRequired (paymentOptional) | | 403 | forbidden | notForbidden (allowed, permitted) | | 404 | notFound | found | | 405 | methodNotAllowed | methodAllowed | | 406 | notAcceptable | acceptable | | 407 | proxyAuthRequired | proxyAuthNotRequired (proxyAuthOptional) | | 408 | requestTimeout | notRequestTimeout (requestFast) | | 409 | conflict | notConflict (match) | | 410 | gone | notGone (present) | | 411 | lengthRequired | lengthNotRequired (lengthOptional) | | 412 | preconditionFailed | preconditionSuccessful (preconditionMet, preconditionPassed) | | 413 | payloadTooLarge | notPayloadTooLarge (payloadSmall) | | 414 | uriTooLong | uriNotTooLong (uriShort) | | 415 | unsupportedMediaType | supportedMediaType | | 416 | rangeNotSatisfiable | rangeSatisfiable | | 417 | expectationFailed | expectationSuccessful (expectationMet, expectationPassed) | | 418 | teapot | notTeapot | | 421 | misdirectedRequest | correctlyDirectedRequest (directedRequest) | | 422 | unprocessableEntity | processableEntity | | 423 | locked | unlocked (open) | | 424 | failedDependency | successfulDependency (dependencyMet, dependencyPassed) | | 425 | tooEarly | notTooEarly (afterSufficientTime, onTime) | | 426 | upgradeRequired | upgradeNotRequired (upgradeOptional) | | 428 | preconditionRequired | preconditionNotRequired (preconditionOptional) | | 429 | tooManyRequests | notTooManyRequests (fewRequests) | | 431 | requestHeaderFieldsTooLarge | requestHeaderFieldsAcceptable (requestHeaderFieldsSmall) | | 451 | unavailableForLegalReasons | availableForLegalReasons |

Server Error Responses (500599)

| Status Code | Function (Aliases) | Negated Function (Aliases) | | ------------------------------------------------------------- | ------------------------------- | --------------------------------------------------------------------------- | | 500 | internalServerError | noError (notInternalServerError) | | 501 | notImplemented | implemented | | 502 | badGateway | goodGateway | | 503 | serviceUnavailable | serviceAvailable | | 504 | gatewayTimeout | notGatewayTimeout (gatewayResponsive) | | 505 | httpVersionNotSupported | httpVersionSupported | | 506 | variantAlsoNegotiates | notVariantAlsoNegotiates (variantNotNegotiating) | | 507 | insufficientStorage | sufficientStorage (storageAvailable) | | 508 | loopDetected | loopNotDetected (noLoop) | | 509 | bandwidthLimitExceeded | bandwidthLimitNotExceeded (bandwidthAvailable) | | 510 | notExtended | extended | | 511 | networkAuthenticationRequired | networkAuthenticationNotRequired (networkAuthenticationOptional) |