all-http-status
v1.0.1
Published
A comprehensive collection of HTTP status codes and their corresponding messages
Maintainers
Readme
HTTP Status Codes
A comprehensive npm package that provides HTTP status codes and their corresponding messages with utility functions for easy use in Node.js and browser applications.
Features
- 📋 Complete collection of HTTP status codes (1xx, 2xx, 3xx, 4xx, 5xx)
- 📝 Human-readable status messages for each code
- 🌐 Cloudflare-specific status codes (520, 521, 522, etc.)
- 📄 Text constants for all status messages
- 🔧 Utility functions for status code validation
- 💪 TypeScript support with full type definitions
- 🌳 Tree-shakeable - Only bundle what you use
- 🚀 Zero dependencies
- 📦 Lightweight and fast
- 🔄 Dual package support (CommonJS + ES Modules)
Installation
npm install @ishwardattmishra/http-status-codesUsage
Basic Usage
const { OK, NOT_FOUND, INTERNAL_SERVER_ERROR, getStatusMessage } = require('@ishwardattmishra/http-status-codes');
console.log(OK); // 200
console.log(NOT_FOUND); // 404
console.log(getStatusMessage(200)); // "OK"
console.log(getStatusMessage(404)); // "Not Found"TypeScript Usage
import {
OK,
NOT_FOUND,
INTERNAL_SERVER_ERROR,
getStatusMessage,
isSuccess,
isClientError
} from '@ishwardattmishra/http-status-codes';
const statusCode: number = 200;
console.log(isSuccess(statusCode)); // true
console.log(getStatusMessage(statusCode)); // "OK"Express.js Example
const express = require('express');
const { OK, NOT_FOUND, INTERNAL_SERVER_ERROR, getStatusMessage } = require('@ishwardattmishra/http-status-codes');
const app = express();
app.get('/api/users/:id', (req, res) => {
try {
// Your logic here
const user = getUserById(req.params.id);
if (!user) {
return res.status(NOT_FOUND).json({
error: getStatusMessage(NOT_FOUND),
message: 'User not found'
});
}
res.status(OK).json(user);
} catch (error) {
res.status(INTERNAL_SERVER_ERROR).json({
error: getStatusMessage(INTERNAL_SERVER_ERROR),
message: 'Something went wrong'
});
}
});Available Status Codes
1xx Informational
CONTINUE(100)SWITCHING_PROTOCOLS(101)PROCESSING(102)EARLY_HINTS(103)
2xx Success
OK(200)CREATED(201)ACCEPTED(202)NON_AUTHORITATIVE_INFORMATION(203)NO_CONTENT(204)RESET_CONTENT(205)PARTIAL_CONTENT(206)MULTI_STATUS(207)ALREADY_REPORTED(208)IM_USED(226)
3xx Redirection
MULTIPLE_CHOICES(300)MOVED_PERMANENTLY(301)FOUND(302)SEE_OTHER(303)NOT_MODIFIED(304)USE_PROXY(305)TEMPORARY_REDIRECT(307)PERMANENT_REDIRECT(308)
4xx Client Errors
BAD_REQUEST(400)UNAUTHORIZED(401)PAYMENT_REQUIRED(402)FORBIDDEN(403)NOT_FOUND(404)METHOD_NOT_ALLOWED(405)NOT_ACCEPTABLE(406)PROXY_AUTHENTICATION_REQUIRED(407)REQUEST_TIMEOUT(408)CONFLICT(409)GONE(410)LENGTH_REQUIRED(411)PRECONDITION_FAILED(412)PAYLOAD_TOO_LARGE(413)URI_TOO_LONG(414)UNSUPPORTED_MEDIA_TYPE(415)RANGE_NOT_SATISFIABLE(416)EXPECTATION_FAILED(417)IM_A_TEAPOT(418)MISDIRECTED_REQUEST(421)UNPROCESSABLE_ENTITY(422)LOCKED(423)FAILED_DEPENDENCY(424)TOO_EARLY(425)UPGRADE_REQUIRED(426)PRECONDITION_REQUIRED(428)TOO_MANY_REQUESTS(429)REQUEST_HEADER_FIELDS_TOO_LARGE(431)UNAVAILABLE_FOR_LEGAL_REASONS(451)
5xx Server Errors
INTERNAL_SERVER_ERROR(500)NOT_IMPLEMENTED(501)BAD_GATEWAY(502)SERVICE_UNAVAILABLE(503)GATEWAY_TIMEOUT(504)HTTP_VERSION_NOT_SUPPORTED(505)VARIANT_ALSO_NEGOTIATES(506)INSUFFICIENT_STORAGE(507)LOOP_DETECTED(508)NOT_EXTENDED(510)NETWORK_AUTHENTICATION_REQUIRED(511)
Cloudflare-Specific Errors
WEB_SERVER_UNKNOWN_ERROR(520)WEB_SERVER_IS_DOWN(521)CONNECTION_TIMED_OUT(522)ORIGIN_IS_UNREACHABLE(523)A_TIMEOUT_OCCURRED(524)SSL_HANDSHAKE_FAILED(525)INVALID_SSL_CERTIFICATE(526)RAILGUN_ERROR(527)ORIGIN_DNS_ERROR(530)
Text Constants
In addition to numeric status codes, the package also exports text constants for all status messages. These are useful when you need direct access to the message strings.
const { OK_TEXT, NOT_FOUND_TEXT, INTERNAL_SERVER_ERROR_TEXT } = require('@ishwardattmishra/http-status-codes');
console.log(OK_TEXT); // "OK"
console.log(NOT_FOUND_TEXT); // "Not Found"
console.log(INTERNAL_SERVER_ERROR_TEXT); // "Internal Server Error"Text Constant Examples
All status codes have corresponding text constants following the pattern {STATUS_NAME}_TEXT:
OK_TEXT→ "OK"CREATED_TEXT→ "Created"BAD_REQUEST_TEXT→ "Bad Request"NOT_FOUND_TEXT→ "Not Found"INTERNAL_SERVER_ERROR_TEXT→ "Internal Server Error"WEB_SERVER_IS_DOWN_TEXT→ "Web Server Is Down"
Utility Functions
getStatusMessage(statusCode)
Returns the human-readable message for a given status code.
getStatusMessage(200); // "OK"
getStatusMessage(404); // "Not Found"
getStatusMessage(999); // undefinedisSuccess(statusCode)
Checks if the status code indicates success (2xx range).
isSuccess(200); // true
isSuccess(201); // true
isSuccess(404); // falseisClientError(statusCode)
Checks if the status code indicates a client error (4xx range).
isClientError(400); // true
isClientError(404); // true
isClientError(200); // falseisServerError(statusCode)
Checks if the status code indicates a server error (5xx range).
isServerError(500); // true
isServerError(502); // true
isServerError(404); // falseisRedirection(statusCode)
Checks if the status code indicates a redirection (3xx range).
isRedirection(301); // true
isRedirection(302); // true
isRedirection(200); // falseisInformational(statusCode)
Checks if the status code indicates an informational response (1xx range).
isInformational(100); // true
isInformational(101); // true
isInformational(200); // falseisCloudflareError(statusCode)
Checks if the status code is a Cloudflare-specific error.
isCloudflareError(520); // true
isCloudflareError(521); // true
isCloudflareError(404); // falsegetStatusCode(message, caseSensitive?)
Get the status code for a given message (reverse lookup).
getStatusCode('OK'); // 200
getStatusCode('Not Found'); // 404
getStatusCode('web server is down'); // 521 (case insensitive by default)
getStatusCode('Bad Request', true); // 400 (case sensitive)
getStatusCode('Unknown Message'); // nullfindStatusByText(searchText, caseSensitive?)
Find status codes that contain the given text in their message.
findStatusByText('error');
// Returns: [
// { code: 500, message: 'Internal Server Error' },
// { code: 520, message: 'Web Server Returned an Unknown Error' },
// { code: 527, message: 'Railgun Error' }
// ]
findStatusByText('timeout');
// Returns: [
// { code: 408, message: 'Request Timeout' },
// { code: 504, message: 'Gateway Timeout' },
// { code: 524, message: 'A Timeout Occurred' }
// ]getStatusCodesInRange(start, end)
Get all status codes within a specific range.
getStatusCodesInRange(200, 204);
// Returns: [
// { code: 200, message: 'OK' },
// { code: 201, message: 'Created' },
// { code: 202, message: 'Accepted' },
// { code: 203, message: 'Non-Authoritative Information' },
// { code: 204, message: 'No Content' }
// ]getStatusCodesByCategory(category)
Get all status codes of a specific category.
getStatusCodesByCategory('success');
// Returns all 2xx status codes
getStatusCodesByCategory('client-error');
// Returns all 4xx status codes
getStatusCodesByCategory('cloudflare');
// Returns all Cloudflare-specific codesisError(statusCode)
Check if a status code indicates an error (4xx or 5xx).
isError(404); // true
isError(500); // true
isError(200); // falseisRetryable(statusCode)
Check if a status code is safe to retry.
isRetryable(500); // true (server errors are retryable)
isRetryable(429); // true (rate limit is retryable)
isRetryable(404); // false (client errors are not retryable)requiresAuth(statusCode)
Check if a status code requires authentication.
requiresAuth(401); // true
requiresAuth(403); // true
requiresAuth(200); // falseisPermanentFailure(statusCode) / isTemporaryFailure(statusCode)
Check if a failure is permanent or temporary.
isPermanentFailure(404); // true
isTemporaryFailure(500); // true
isTemporaryFailure(429); // truegetStatusCategory(statusCode)
Get the category of an HTTP status code.
getStatusCategory(200); // "Success"
getStatusCategory(404); // "Client Error"
getStatusCategory(521); // "Cloudflare Error"isCacheable(statusCode)
Check if a status code is cacheable by default (RFC 7231).
isCacheable(200); // true
isCacheable(404); // true
isCacheable(500); // falseisSuccessNoContent(statusCode)
Check if successful but has no content.
isSuccessNoContent(204); // true
isSuccessNoContent(304); // true
isSuccessNoContent(200); // falsegetRecommendedStatus(scenario)
Get recommended status codes for common scenarios.
getRecommendedStatus('created'); // 201
getRecommendedStatus('updated'); // 200
getRecommendedStatus('deleted'); // 204
getRecommendedStatus('validation_failed'); // 400
getRecommendedStatus('rate_limited'); // 429formatStatus(statusCode)
Format a status code with its message for display.
formatStatus(404); // "404 Not Found"
formatStatus(200); // "200 OK"
formatStatus(999); // "999 Unknown Status"isValidStatusCode(statusCode)
Check if a status code is valid.
isValidStatusCode(200); // true
isValidStatusCode(999); // false
isValidStatusCode('abc'); // falseSTATUS_MESSAGES Object
Access the complete mapping of status codes to messages:
const { STATUS_MESSAGES } = require('@ishwardattmishra/http-status-codes');
console.log(STATUS_MESSAGES[200]); // "OK"
console.log(STATUS_MESSAGES[404]); // "Not Found"
// Iterate through all status codes
Object.entries(STATUS_MESSAGES).forEach(([code, message]) => {
console.log(`${code}: ${message}`);
});Testing
This package includes comprehensive unit tests to ensure reliability:
# Run all tests
npm test
# Run individual test suites
npm run test:commonjs # CommonJS module tests
npm run test:es6 # ES6 module tests
npm run test:performance # Performance benchmarks
# Watch mode for development
npm run test:watchTest Coverage
- ✅ 46 Unit Tests covering all functions and edge cases
- ✅ Performance Tests ensuring optimal speed (< 0.01ms per operation)
- ✅ Tree-shaking Validation for ES6 modules
- ✅ Memory Leak Detection for stability
- ✅ Integration Scenarios for real-world usage
Browser Support
This package works in both Node.js and browser environments. For browser usage, you can use it with bundlers like Webpack, Rollup, or Parcel.
Performance
All utility functions are highly optimized:
getStatusMessage(): < 0.001ms per operationgetStatusCode(): < 0.003ms per operationfindStatusByText(): < 0.004ms per operation- Zero memory leaks in continuous usage
License
MIT
Contributing
Contributions are welcome! Please feel free to submit a Pull Request. Make sure to run npm test before submitting.
