http-status-codes

repository·master·Indexed 22 days ago

https://github.com/prettymuchbryce/http-status-codes

A lightweight, dependency-free library for TypeScript and JavaScript providing constants for HTTP status codes and reason phrases, based on the Java Apache HttpStatus API. Version 2.3.0 includes the StatusCodes and ReasonPhrases objects, along with utility functions like getReasonPhrase() and getStatusCode() to map between numeric codes and human-readable text.

Tokens
4.1K
Snippets
9
Records
11
Agent score
78%

What's inside http-status-codes

  1. Migrate from v1.x.x to v2.x.x

    master

    When upgrading from version 1 to version 2, note the following changes:

    Breaking Change: 'Server Error' vs 'Internal Server Error'

    In v2, the reason phrase for status code 500 has changed from "Server Error" to "Internal Server Error" to comply with RFC7231. If your code relies on the exact string returned by getReasonPhrase(500) or getReasonPhrase('Server Error'), you must update it.

    The function getStatusText has been renamed to getReasonPhrase. While the old name may still work, it is recommended to rename all instances to getReasonPhrase().

    In v1, status codes were exported directly (e.g., HttpStatus.OK). In v2, they are grouped under the StatusCodes object (e.g., StatusCodes.OK). While previous direct exports are still available, they are no longer being updated. It is recommended to migrate to the StatusCodes object for better TypeScript support.

  2. Migrate from legacy status code constants to StatusCodes

    master

    The direct export of status code constants (e.g., OK, NOT_FOUND, INTERNAL_SERVER_ERROR) is deprecated and maintained only for compatibility with v1.x.x.

    To ensure your code is up to date and avoids using deprecated symbols, you should migrate these individual constants to the StatusCodes object.

    Migration Mapping Example:

    • Instead of OK, use StatusCodes.OK
    • Instead of NOT_FOUND, use StatusCodes.NOT_FOUND
    • Instead of BAD_REQUEST, use StatusCodes.BAD_REQUEST

    Do not add any new status codes to the legacy exports.

  3. Use http-status-codes in Express.js

    master

    You can use StatusCodes to set response status codes and ReasonPhrases or getReasonPhrase() to send the corresponding human-readable reason phrases. You can also use getStatusCode() to retrieve a numeric code from a reason phrase string.

    import {
    	ReasonPhrases,
    	StatusCodes,
    	getReasonPhrase,
    	getStatusCode,
    } from 'http-status-codes';
    
    // Using constants for status and reason phrases
    response
    	.status(StatusCodes.OK)
    	.send(ReasonPhrases.OK);
    
    // Using getReasonPhrase with a status code
    response
    	.status(StatusCodes.INTERNAL_SERVER_ERROR)
    	.send({
    		error: getReasonPhrase(StatusCodes.INTERNAL_SERVER_ERROR)
    	});
    
    // Using getStatusCode with a reason phrase string
    response
    	.status(getStatusCode('Internal Server Error'))
    	.send({
    		error: 'Internal Server Error'
    	});
  4. Reference HTTP Status Codes, Constants, and Reason Phrases

    master

    The following table maps numeric HTTP status codes to their library constants and standard reason phrases.

    | Code | Constant                        | Reason Phrase                   |
    | ---- | ------------------------------- | ------------------------------- |
    | 100  | CONTINUE                        | Continue                        |
    | 101  | SWITCHING_PROTOCOLS             | Switching Protocols             |
    | 102  | PROCESSING                      | Processing                      |
    | 103  | EARLY_HINTS                     | Early Hints                     |
    | 200  | OK                              | OK                              |
    | 201  | CREATED                         | Created                         |
    | 202  | ACCEPTED                        | Accepted                        |
    | 203  | NON_AUTHORITATIVE_INFORMATION   | Non Authoritative Information   |
    | 204  | NO_CONTENT                      | No Content                      |
    | 205  | RESET_CONTENT                   | Reset Content                   |
    | 206  | PARTIAL_CONTENT                 | Partial Content                 |
    | 207  | MULTI_STATUS                    | Multi-Status                     |
    | 300  | MULTIPLE_CHOICES                | Multiple Choices                 |
    | 301  | MOVED_PERMANENTLY               | Moved Permanently               |
    | 302  | MOVED_TEMPORARILY               | Moved Temporarily               |
    | 303  | SEE_OTHER                       | See Other                       |
    | 304  | NOT_MODIFIED                    | Not Modified                     |
    | 305  | USE_PROXY                       | Use Proxy                       |
    | 307  | TEMPORARY_REDIRECT              | Temporary Redirect              |
    | 308  | PERMANENT_REDIRECT              | Permanent Redirect              |
    | 400  | BAD_REQUEST                     | Bad Request                     |
    | 401  | UNAUTHORIZED                    | Unauthorized                    |
    | 402  | PAYMENT_REQUIRED               | Payment Required                 |
    | 403  | FORBIDDEN                       | Forbidden                       |
    | 404  | NOT_FOUND                       | Not Found                       |
    | 405  | METHOD_NOT_ALLOWED              | Method Not Allowed              |
    | 406  | NOT_ACCEPTABLE                  | Not Acceptable                  |
    | 407  | PROXY_AUTHENTICATION_REQUIRED   | Proxy Authentication Required   |
    | 408  | REQUEST_TIMEOUT                | Request Timeout                 |
    | 409  | CONFLICT                        | Conflict                        |
    | 410  | GONE                            | Gone                            |
    | 411  | LENGTH_REQUIRED                 | Length Required                 |
    | 412  | PRECONDITION_FAILED             | Precondition Failed             |
    | 413  | REQUEST_TOO_LONG                | Request Entity Too Large        |
    | 414  | REQUEST_URI_TOO_LONG            | Request-URI Too Long            |
    | 415  | UNSUPPORTED_MEDIA_TYPE          | Unsupported Media Type          |
    | 416  | REQUESTED_RANGE_NOT_SATISFIABLE | Requested Range Not Satisfiable |
    | 417  | EXPECTATION_FAILED              | Expectation Failed              |
    | 418  | IM_A_TEAPOT                     | I'm a teapot                    |
    | 419  | INSUFFICIENT_SPACE_ON_RESOURCE  | Insufficient Space on Resource  |
    | 420  | METHOD_FAILURE                  | Method Failure                  |
    | 421  | MISDIRECTED_REQUEST             | Misdirected Request             |
    | 422  | UNPROCESSABLE_ENTITY           | Unprocessable Entity            |
    | 423  | LOCKED                          | Locked                          |
    | 424  | FAILED_DEPENDENCY              | Failed Dependency               |
    | 426  | UPGRADE_REQUIRED               | Upgrade Required               |
    | 428  | PRECONDITION_REQUIRED          | Precondition Required           |
    | 429  | TOO_MANY_REQUESTS               | Too Many Requests               |
    | 431  | REQUEST_HEADER_FIELDS_TOO_LARGE | Request Header Fields Too Large |
    | 451  | UNAVAILABLE_FOR_LEGAL_REASONS   | Unavailable For Legal Reasons   |
    | 500  | INTERNAL_SERVER_ERROR           | Internal Server Error           |
    | 501  | NOT_IMPLEMENTED                 | Not Implemented                 |
    | 502  | BAD_GATEWAY                     | Bad Gateway                     |
    | 503  | SERVICE_UNAVAILABLE             | Service Unavailable             |
    | 504  | GATEWAY_TIMEOUT                 | Gateway Timeout                 |
    | 505  | HTTP_VERSION_NOT_SUPPORTED      | HTTP Version Not Supported      |
    | 507  | INSUFFICIENT_STORAGE            | Insufficient Storage            |
    | 511  | NETWORK_AUTHENTICATION_REQUIRED | Network Authentication Required |
  5. Use the default export for legacy and utility access

    master

    The library provides a default export that combines legacyCodes with the utility functions getStatusCode and getStatusText. This is useful for a single-import approach that includes both older code mappings and modern utility methods.

    import httpStatusCodes from 'http-status-codes';
    
    // Accessing legacy codes
    const legacyCode = httpStatusCodes.SOME_LEGACY_CODE;
    
    // Accessing utilities
    const text = httpStatusCodes.getStatusText(200);
  6. Get the status code for a reason phrase with getStatusCode()

    master

    Use getStatusCode(reasonPhrase) to retrieve the numeric HTTP status code associated with a specific reason phrase (e.g., "OK").

    Note: If the provided reason phrase is not recognized, this function will throw an Error with the message: Reason phrase does not exist: ${reasonPhrase}.

    import { getStatusCode } from 'http-status-codes';
    
    const code = getStatusCode('Bad Request'); // returns 400
  7. Access HTTP status codes and reason phrases

    master

    The library provides two primary ways to access HTTP status code information: using the StatusCodes object for numeric codes and the ReasonPhrases object for the associated text descriptions. These are exported as named constants.

    import { StatusCodes, ReasonPhrases } from 'http-status-codes';
    
    // Example usage of StatusCodes
    const code = StatusCodes.OK; // 200
    
    // Example usage of ReasonPhrases
    const phrase = ReasonPhrases[StatusCodes.OK]; // 'OK'
  8. Get status code or text using utility functions

    master

    You can use utility functions to programmatically retrieve status information.

    • getStatusCode(code: number): Returns the status code if valid.
    • getStatusText(code: number): Returns the reason phrase/text associated with the status code.
    • getReasonPhrase(code: number): An alias for retrieving the reason phrase.
    import { getStatusCode, getStatusText, getReasonPhrase } from 'http-status-codes';
    
    const code = getStatusCode(200);
    const text = getStatusText(200);
    const phrase = getReasonPhrase(200);
  9. Get the reason phrase for a status code with getReasonPhrase()

    master

    Use getReasonPhrase(statusCode) to retrieve the human-readable reason phrase (e.g., "OK" or "Bad Request") associated with a specific HTTP status code.

    Note: This function accepts both number and string types for the statusCode. If the provided status code is not recognized by the library, it will throw an Error with the message: Status code does not exist: ${statusCode}.

    import { getReasonPhrase } from 'http-status-codes';
    
    const phrase = getReasonPhrase(200); // returns "OK"
    const phraseFromString = getReasonPhrase('404'); // returns "Not Found"