node-http-status
v1.3.0
Published
Simple and intuitive HTTP response status codes
Maintainers
Readme
A simple and intuitive HTTP response status code library for Node.js.
Why choose node-http-status?
Zero dependencies. Zero runtime overhead. Just plain objects.
✅ Simple: No complex APIs to learn - just import and use
✅ Lightweight: Under 3KB minified, zero dependencies
✅ Flexible: Multiple access patterns (camelCase, UPPERCASE, numeric)
✅ Customizable: Create your own response object format with createCustomHttpStatus
✅ Localized: Built-in support for multiple languages (EN, JA, ES, DE)
✅ TypeScript-first: Full type safety out of the box
✅ Framework-agnostic: Works with Express, Fastify, Next.js, or any Node.js app
Installation
npm install node-http-statusUsage
ES Modules (Recommended)
import httpStatus from 'node-http-status'
// Get status information - multiple ways to access the same response
console.log(httpStatus.ok)
console.log(httpStatus.OK) // UPPERCASE alias
console.log(httpStatus[200]) // Numeric alias
// All output: { status: 200, code: 'OK', message: 'The request has succeeded' }
// All three are the same object
console.log(httpStatus.OK === httpStatus.ok === httpStatus[200])
// Output: true
console.log(httpStatus.forbidden)
console.log(httpStatus.FORBIDDEN)
console.log(httpStatus[403])
// All output: { status: 403, code: 'FORBIDDEN', message: 'The server understood the request but refuses to authorize it' }
// Access just the status code
console.log(httpStatus.ok.status)
// Output: 200
// Use in Express.js
app.get('/api/users', (req, res) => {
const users = getUsersFromDatabase()
res.status(httpStatus.ok.status).json({
...httpStatus.ok,
data: users
})
})
// Handle errors
app.get('/api/users/:id', (req, res) => {
const user = findUser(req.params.id)
if (!user) {
return res.status(httpStatus.notFound.status).json(httpStatus.notFound)
}
res.json({ ...httpStatus.ok, data: user })
})CommonJS
// Method 1: Dynamic import (Recommended for newer Node.js versions)
const httpStatus = await import('node-http-status').then(m => m.default)
// Method 2: Require (works with dual exports)
const httpStatus = require('node-http-status')
// Usage is identical to ES modules
console.log(httpStatus.ok)
console.log(httpStatus.OK) // UPPERCASE alias
console.log(httpStatus[200]) // Numeric alias
// All output: { status: 200, code: 'OK', message: 'The request has succeeded' }
// Use in Express.js with CommonJS
app.get('/api/users', (req, res) => {
const users = getUsersFromDatabase()
res.status(httpStatus.ok.status).json({
...httpStatus.ok,
data: users
})
})Note: If you get import errors with CommonJS, ensure:
- You're using Node.js 18+ (required by this package)
- Your project doesn't have conflicting module settings
- Consider using dynamic imports for better compatibility
Available Status Codes
2xx Success
ok- 200 OKcreated- 201 Createdaccepted- 202 AcceptednoContent- 204 No ContentpartialContent- 206 Partial Content
3xx Redirection
moved- 301 Moved Permanentlyfound- 302 FoundnotModified- 304 Not ModifiedtemporaryRedirect- 307 Temporary RedirectpermanentRedirect- 308 Permanent Redirect
4xx Client Error
badRequest- 400 Bad Requestunauthorized- 401 Unauthorizedforbidden- 403 ForbiddennotFound- 404 Not FoundmethodNotAllowed- 405 Method Not AllowednotAcceptable- 406 Not AcceptablerequestTimeout- 408 Request Timeoutconflict- 409 Conflictgone- 410 GonelengthRequired- 411 Length RequiredpreconditionFailed- 412 Precondition FailedpayloadTooLarge- 413 Payload Too LargeuriTooLong- 414 URI Too LongunsupportedMediaType- 415 Unsupported Media TyperangeNotSatisfiable- 416 Range Not SatisfiableexpectationFailed- 417 Expectation FailedimATeapot- 418 I'm a teapotunprocessableEntity- 422 Unprocessable EntityupgradeRequired- 426 Upgrade RequiredpreconditionRequired- 428 Precondition RequiredtooManyRequests- 429 Too Many RequestsrequestHeaderFieldsTooLarge- 431 Request Header Fields Too LargeunavailableForLegalReasons- 451 Unavailable For Legal Reasons
5xx Server Error
internalServerError- 500 Internal Server ErrornotImplemented- 501 Not ImplementedbadGateway- 502 Bad GatewayserviceUnavailable- 503 Service UnavailablegatewayTimeout- 504 Gateway TimeouthttpVersionNotSupported- 505 HTTP Version Not SupportednetworkAuthenticationRequired- 511 Network Authentication Required
Localization
The library supports multiple languages for status code messages. Import locale-specific versions to get translated messages while keeping the same API.
Available Locales
- English (default):
node-http-status - Japanese:
node-http-status/locale/ja - Spanish:
node-http-status/locale/es - German:
node-http-status/locale/de
Usage
// ES Modules
// Default English
import httpStatus from 'node-http-status'
console.log(httpStatus.FORBIDDEN.message)
// "The server understood the request but refuses to authorize it"
// Japanese
import httpStatus from 'node-http-status/locale/ja'
console.log(httpStatus.FORBIDDEN.message)
// "サーバーはリクエストを理解したが、承認を拒否した。"
// Spanish
import httpStatus from 'node-http-status/locale/es'
console.log(httpStatus.FORBIDDEN.message)
// "El servidor entendió la solicitud pero se niega a autorizarla"
// German
import httpStatus from 'node-http-status/locale/de'
console.log(httpStatus.FORBIDDEN.message)
// "Der Server verstand die Anfrage, verweigert aber die Autorisierung"// CommonJS
// Default English
const httpStatus = require('node-http-status')
console.log(httpStatus.FORBIDDEN.message)
// "The server understood the request but refuses to authorize it"
// Japanese
const httpStatus = require('node-http-status/locale/ja')
console.log(httpStatus.FORBIDDEN.message)
// "サーバーはリクエストを理解したが、承認を拒否した。"
// Spanish
const httpStatus = require('node-http-status/locale/es')
console.log(httpStatus.FORBIDDEN.message)
// "El servidor entendió la solicitud pero se niega a autorizarla"
// German
const httpStatus = require('node-http-status/locale/de')
console.log(httpStatus.FORBIDDEN.message)
// "Der Server verstand die Anfrage, verweigert aber die Autorisierung"Locale API
Each locale provides the exact same API as the default English version:
import httpStatus from 'node-http-status/locale/ja'
// All access patterns work the same
console.log(httpStatus.forbidden.message) // camelCase
console.log(httpStatus.FORBIDDEN.message) // UPPERCASE
console.log(httpStatus[403].message) // numeric
// Status codes and code names remain unchanged
console.log(httpStatus.FORBIDDEN.status) // 403
console.log(httpStatus.FORBIDDEN.code) // "FORBIDDEN"Express.js with Locales
import express from 'express'
import httpStatus from 'node-http-status/locale/es'
const app = express()
app.get('/api/data', (req, res) => {
// Send Spanish error messages to Spanish-speaking users
res.status(httpStatus.notFound.status).json(httpStatus.notFound)
// Response: { status: 404, code: 'NOT_FOUND', message: 'No se pudo encontrar el recurso solicitado' }
})Custom Formatters
Need a different response object structure? Use createCustomHttpStatus to define your own format while keeping all the convenience of aliases and status codes.
import { createCustomHttpStatus } from 'node-http-status'
// Create a custom formatter function
const customHttp = createCustomHttpStatus((status, code, message) => ({
response: {
error: code,
message: message
},
statusCode: status
}))
// Use it just like the regular httpStatus object
console.log(customHttp.internalServerError)
// { response: { error: 'INTERNAL_SERVER_ERROR', message: '...' }, statusCode: 500 }
// All aliases work the same way
console.log(customHttp.INTERNAL_SERVER_ERROR === customHttp.internalServerError) // true
console.log(customHttp[500] === customHttp.internalServerError) // trueREST API Format Example
import { createCustomHttpStatus } from 'node-http-status'
const apiFormat = createCustomHttpStatus((status, code, message) => ({
success: status < 400,
statusCode: status,
error: status >= 400 ? {
type: code,
message: message
} : null,
data: null
}))
// Success response
console.log(apiFormat.ok)
// { success: true, statusCode: 200, error: null, data: null }
// Error response
console.log(apiFormat.badRequest)
// { success: false, statusCode: 400, error: { type: 'BAD_REQUEST', message: '...' }, data: null }Express.js with Custom Format
import express from 'express'
import { createCustomHttpStatus } from 'node-http-status'
const app = express()
// Create Express-friendly format
const expressFormat = createCustomHttpStatus((status, code, message) => ({
status,
error: {
code: code,
detail: message
}
}))
app.get('/api/users/:id', (req, res) => {
const user = findUser(req.params.id)
if (!user) {
const notFoundResponse = expressFormat.notFound
return res.status(notFoundResponse.status).json(notFoundResponse.error)
}
const okResponse = expressFormat.ok
res.status(okResponse.status).json({
...okResponse.error,
user
})
})TypeScript with Custom Formatters
import { createCustomHttpStatus, type HttpStatusFormatter } from 'node-http-status'
// Define your custom response type
interface CustomResponse {
httpStatus: number
errorType: string
description: string
timestamp: string
}
// Create type-safe formatter
const formatter: HttpStatusFormatter<CustomResponse> = (status, code, message) => ({
httpStatus: status,
errorType: code,
description: message,
timestamp: new Date().toISOString()
})
const customHttp = createCustomHttpStatus(formatter)
// Full type safety
const response: CustomResponse = customHttp.forbidden
// response.httpStatus is number
// response.errorType is string
// response.description is string
// response.timestamp is stringAPI Reference
Each status code returns a consistent object structure:
interface HttpStatus {
status: number; // The numeric HTTP status code
code: string; // The standard HTTP status phrase
message: string; // A human-readable description
}TypeScript Support
Built with TypeScript and includes complete type definitions out of the box.
// ES Modules
import httpStatus from 'node-http-status'
const response: HttpStatus = httpStatus.ok
// response.status is typed as number
// response.code is typed as string
// response.message is typed as string
// CommonJS
const httpStatus = require('node-http-status')
const response: HttpStatus = httpStatus.ok
// Fully typed in both module systems
// The httpStatus object is typed as HttpStatusObject which includes all aliases
const statusHandler = (httpCodes: HttpStatusObject) => {
console.log(httpCodes.OK === httpCodes.ok === httpCodes[200]) // true
}
statusHandler(httpStatus)Examples
Express.js API
import express from 'express'
import httpStatus from 'node-http-status'
const app = express()
// Success response
app.get('/health', (req, res) => {
res.status(httpStatus.ok.status).json({
...httpStatus.ok,
timestamp: new Date().toISOString()
})
})
// Error handling
app.use((err, req, res, next) => {
console.error(err)
res.status(httpStatus.internalServerError.status).json(httpStatus.internalServerError)
})Fetch API
import httpStatus from 'node-http-status'
const response = await fetch('/api/data')
if (response.status === httpStatus.notFound.status) {
console.log('Resource not found')
} else if (response.status === httpStatus.ok.status) {
const data = await response.json()
// Handle success
}License
MIT
