http-code-responses
v0.1.1
Published
Readable HTTP status code constants with reason phrases and helpers.
Downloads
6
Maintainers
Readme
🚀 http-code-responses
Readable HTTP status code constants with reason phrases and helpers
Features • Installation • Usage • API • Roadmap • Contributing
✨ Features
- ✅ Concise constants for every standard HTTP status code
- 📝 Reason phrases mapped to each code (e.g.,
404→"Not Found") - 🪶 Tiny footprint - zero runtime dependencies
- 📦 Universal - ESM + CJS + TypeScript types
- 🔍 Type-safe - Full TypeScript support with autocomplete
- 🎯 Familiar naming - Inspired by Symfony HttpFoundation's Response constants
- ⚡ Tree-shakeable - Only bundle what you use
- 🧪 Well-tested - 100% code coverage
📦 Installation
# npm
npm install http-code-responses
# pnpm
pnpm add http-code-responses
# yarn
yarn add http-code-responses
# bun
bun add http-code-responses🚀 Usage
JavaScript (ESM)
import { StatusCodes, ReasonPhrases, getReasonPhrase } from 'http-code-responses'
// Express.js example
app.get('/health', (req, res) => {
res.status(StatusCodes.OK).send('ok')
})
// Get reason phrases
console.log(ReasonPhrases[StatusCodes.NOT_FOUND]) // "Not Found"
console.log(getReasonPhrase(422)) // "Unprocessable Content"JavaScript (CommonJS)
const { StatusCodes, ReasonPhrases, getReasonPhrase } = require('http-code-responses')
res.status(StatusCodes.CREATED).json({ id })
console.log(ReasonPhrases[StatusCodes.BAD_REQUEST]) // "Bad Request"
console.log(getReasonPhrase(503)) // "Service Unavailable"TypeScript
import { StatusCodes, type StatusCode, type StatusName } from 'http-code-responses'
function sendResponse(code: StatusCode) {
// code is type-safe with full autocomplete support
return { statusCode: code }
}
sendResponse(StatusCodes.NO_CONTENT)
const statusName: StatusName = 'INTERNAL_SERVER_ERROR'Framework Examples
import express from 'express'
import { StatusCodes, getReasonPhrase } from 'http-code-responses'
const app = express()
app.get('/api/users/:id', async (req, res) => {
const user = await findUser(req.params.id)
if (!user) {
return res.status(StatusCodes.NOT_FOUND).json({
error: getReasonPhrase(StatusCodes.NOT_FOUND)
})
}
res.status(StatusCodes.OK).json(user)
})import Fastify from 'fastify'
import { StatusCodes } from 'http-code-responses'
const fastify = Fastify()
fastify.get('/api/health', async (request, reply) => {
return reply.code(StatusCodes.OK).send({ status: 'healthy' })
})import { NextApiRequest, NextApiResponse } from 'next'
import { StatusCodes } from 'http-code-responses'
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method !== 'POST') {
return res.status(StatusCodes.METHOD_NOT_ALLOWED).json({
error: 'Method not allowed'
})
}
res.status(StatusCodes.CREATED).json({ success: true })
}import { Hono } from 'hono'
import { StatusCodes } from 'http-code-responses'
const app = new Hono()
app.post('/api/data', async (c) => {
const data = await c.req.json()
// Process data...
return c.json({ success: true }, StatusCodes.CREATED)
})📖 API
StatusCodes
Object with named constants for all standard HTTP status codes.
StatusCodes.OK // 200
StatusCodes.CREATED // 201
StatusCodes.NO_CONTENT // 204
StatusCodes.BAD_REQUEST // 400
StatusCodes.UNAUTHORIZED // 401
StatusCodes.FORBIDDEN // 403
StatusCodes.NOT_FOUND // 404
StatusCodes.INTERNAL_SERVER_ERROR // 500
// ... and many moreAlso includes common aliases:
UNPROCESSABLE_ENTITY(422)PAYLOAD_TOO_LARGE(413)REQUEST_URI_TOO_LONG(414)
ReasonPhrases
ReasonPhrases: Record<number, string>Maps status codes to their standard reason phrases.
ReasonPhrases[200] // "OK"
ReasonPhrases[404] // "Not Found"
ReasonPhrases[500] // "Internal Server Error"getReasonPhrase(code: number)
Returns the reason phrase for a given status code.
getReasonPhrase(200) // "OK"
getReasonPhrase(404) // "Not Found"
getReasonPhrase(9999) // undefined (unknown code)getStatusCode(name: string)
Returns the numeric code for a given constant name.
getStatusCode('OK') // 200
getStatusCode('NOT_FOUND') // 404
getStatusCode('INVALID') // undefinedisStatusCode(value: number)
Type guard to check if a number is a known status code.
if (isStatusCode(code)) {
// TypeScript knows code is a valid StatusCode
console.log(getReasonPhrase(code))
}🗺️ Roadmap
We're constantly improving http-code-responses. Here's what's on the horizon:
🎯 Planned Features
[ ] Status Code Categories - Helper functions to check code types:
isInformational(code)- 1xx codesisSuccess(code)- 2xx codesisRedirection(code)- 3xx codesisClientError(code)- 4xx codesisServerError(code)- 5xx codes
[ ] Custom Status Codes - Support for non-standard codes used by specific services:
- Cloudflare status codes (520-527)
- AWS-specific codes
- Custom enterprise codes
[ ] Response Builders - Convenient response object factories:
createErrorResponse(StatusCodes.NOT_FOUND, { details: '...' }) createSuccessResponse(StatusCodes.OK, data)[ ] HTTP/2 & HTTP/3 Support - Additional status codes and features specific to newer protocols
[ ] Localization - Reason phrases in multiple languages:
getReasonPhrase(404, 'es') // "No Encontrado" getReasonPhrase(404, 'fr') // "Non Trouvé"[ ] Status Code Recommendations - Helper to suggest appropriate status codes:
suggestStatusCode({ operation: 'create', success: true }) // 201 suggestStatusCode({ operation: 'delete', success: true }) // 204[ ] OpenAPI/Swagger Integration - Generate OpenAPI response schemas from status codes
[ ] Middleware Helpers - Framework-specific middleware for common patterns:
- Auto-set reason phrases in response headers
- Status code validation
- Logging with status code context
💡 Nice to Have
- [ ] CLI tool for status code lookup
- [ ] Browser extension for quick reference
- [ ] Interactive documentation site
- [ ] Performance benchmarks vs alternatives
- [ ] Code generation for other languages (Python, Go, Rust)
🚀 Recently Completed
- ✅ Full TypeScript support with type guards
- ✅ ESM + CJS dual package support
- ✅ Zero runtime dependencies
- ✅ 100% test coverage
- ✅ Modern HTTP specification alignment
Want to contribute? Check out our Contributing Guide or open an issue to discuss new features!
🤔 Why http-code-responses?
The Problem
// ❌ Magic numbers are hard to read
res.status(422).json({ error: 'Invalid data' })
// ❌ Easy to make typos
res.status(StatusCodes.UNPROCESSABLE_ENTITTY).json(...)
// ❌ Inconsistent across projects
const NOT_FOUND = 404 // defined in every projectThe Solution
// ✅ Readable, typed, consistent
import { StatusCodes } from 'http-code-responses'
res.status(StatusCodes.UNPROCESSABLE_ENTITY).json({ error: 'Invalid data' })Comparison
| Feature | http-code-responses | http-status-codes | statuses | |---------|---------------------|-------------------|----------| | TypeScript Support | ✅ Full | ⚠️ Partial | ❌ No | | ESM + CJS | ✅ | ✅ | ✅ | | Reason Phrases | ✅ | ✅ | ✅ | | Type Guards | ✅ | ❌ | ❌ | | Helper Functions | ✅ | ⚠️ Limited | ✅ | | Bundle Size | 🪶 <2KB | ~3KB | ~2KB | | Zero Dependencies | ✅ | ✅ | ✅ | | Active Maintenance | ✅ | ⚠️ Sporadic | ✅ |
🤝 Contributing
Contributions are welcome! Here's how you can help:
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Make your changes and add tests
- Run tests:
npm test - Check types:
npm run typecheck - Commit your changes:
git commit -m 'feat: add amazing feature' - Push to the branch:
git push origin feature/amazing-feature - Open a Pull Request
Development Setup
# Clone the repository
git clone https://github.com/iamgerwin/http-code-responses.git
cd http-code-responses
# Install dependencies
npm install
# Run tests
npm test
# Run tests in watch mode
npm run test:watch
# Check TypeScript types
npm run typecheck
# Build the project
npm run buildCommit Convention
We use Conventional Commits:
feat:- New featuresfix:- Bug fixesdocs:- Documentation changestest:- Test changeschore:- Tooling/config changes
📄 License
MIT License - see the LICENSE file for details.
💖 Acknowledgments
- Inspired by Symfony HttpFoundation
- HTTP status code specifications from IANA
- Built with TypeScript, tsup, and Vitest
🔗 Related Projects
- http-status-codes - Alternative HTTP status code library
- statuses - HTTP status utility
Made with ❤️ by developers, for developers
If you find this package useful, please consider giving it a ⭐ on GitHub!
