HTTP Status Codes Constants

2.3.0 · active · verified Wed Apr 22

http-status-codes is a JavaScript/TypeScript library that provides constants for HTTP status codes and their corresponding reason phrases. It is currently at version 2.3.0 and maintains a regular release cadence, primarily adding new RFC-defined status codes and minor improvements. Key differentiators include its complete lack of external dependencies, its full support for modern JavaScript and TypeScript environments, and its comprehensive coverage of status codes defined across various RFCs (like RFC1945, RFC2616, RFC2518, RFC6585, RFC7538, RFC8297, RFC7231, RFC7540). The library is designed to be highly tree-shakable, reducing bundle sizes for applications only using a subset of its features. It also offers utility functions to retrieve reason phrases from codes and vice versa, making it a robust and convenient tool for handling HTTP responses.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates importing and using status code constants, reason phrases, and utility functions to manage HTTP responses.

import { StatusCodes, ReasonPhrases, getReasonPhrase, getStatusCode } from 'http-status-codes';

// Example usage with a hypothetical 'response' object (e.g., from Express)
const response = {
  _status: 200,
  _data: '',
  status(code) {
    this._status = code;
    return this;
  },
  send(data) {
    this._data = data;
    console.log(`Status: ${this._status}, Body: ${JSON.stringify(this._data)}`);
  }
};

// Send a successful response
response
  .status(StatusCodes.OK)
  .send(ReasonPhrases.OK);

// Handle an internal server error
response
  .status(StatusCodes.INTERNAL_SERVER_ERROR)
  .send({
    error: getReasonPhrase(StatusCodes.INTERNAL_SERVER_ERROR)
  });

// Get status code from a reason phrase string
const codeFromPhrase = getStatusCode('Bad Request');
response
  .status(codeFromPhrase)
  .send({
    error: 'An unknown error occurred.'
  });

view raw JSON →