HTTP Status Codes for TypeScript

2.0.1 · active · verified Tue Apr 21

http-status-ts is a lightweight, isomorphic utility library designed for convenient access to standard HTTP status codes within TypeScript projects. It provides a comprehensive list of HTTP status codes as a TypeScript enum (`HttpStatus`) and a helper function (`httpStatusTextByCode`) to retrieve the corresponding human-readable text description. Currently stable at version 2.0.1, the library maintains a steady cadence of releases focused on stability and minor enhancements. Its primary differentiation lies in its explicit TypeScript-first design, providing strong type safety out-of-the-box for both Node.js and browser environments, unlike some plain JavaScript alternatives that may require manual type definitions.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates importing and utilizing both the `HttpStatus` enum to retrieve numeric codes and the `httpStatusTextByCode` function to obtain human-readable descriptions, including a conceptual example of their use in an HTTP response.

import { HttpStatus, httpStatusTextByCode } from 'http-status-ts';

// Get a status code's numeric value from the enum
const notFoundCode = HttpStatus.NOT_FOUND;
console.log(`The numeric code for 'Not Found' is: ${notFoundCode}`); // Output: 404

// Get the text description for a specific status code
const okText = httpStatusTextByCode(HttpStatus.OK);
console.log(`The text description for ${HttpStatus.OK} is: "${okText}"`); // Output: "OK"

// Example: Dynamically getting text for a user-input code (simulated)
const userProvidedCode = 500;
const errorMessage = httpStatusTextByCode(userProvidedCode);
console.log(`For code ${userProvidedCode}, the error message is: "${errorMessage}"`); // Output: "Internal Server Error"

// Example using status codes in a conceptual HTTP response
interface MockResponse {
  status: (code: number) => { send: (message: string) => void };
}

const mockResponse: MockResponse = {
  status: (code: number) => ({
    send: (message: string) => {
      console.log(`[HTTP Response Simulator] Status: ${code}, Body: ${message}`);
    }
  })
};

const createSuccess = HttpStatus.CREATED;
mockResponse.status(createSuccess).send(httpStatusTextByCode(createSuccess));

const clientError = HttpStatus.BAD_REQUEST;
mockResponse.status(clientError).send(httpStatusTextByCode(clientError));

view raw JSON →