fourohfour
v1.2.0
Published
HTTP status codes as typed constants (Status.NOT_FOUND is the type 404), RFC 9110 reason phrases, lookups, predicates like isRetryable, and an HttpError that serializes to RFC 9457 problem+json. Tree-shakeable, zero dependencies.
Downloads
649
Maintainers
Readme
fourohfour
HTTP status codes as typed constants, with reason phrases, lookups, helper checks and an error class.
fourohfour gives you every HTTP status code as a named constant, with the current reason phrase from RFC 9110 (the HTTP standard). It also answers common questions, such as "should I retry this request?". Its HttpError class turns into RFC 9457 problem details, a standard JSON format for API errors. Use it in servers, API clients and anywhere you check or send status codes.
Features
- Typed constants:
Status.OKhas the type200, notnumber, so TypeScript can narrowswitchstatements and unions. - Current names: every IANA-registered code with its RFC 9110 phrase (413 Content Too Large, 422 Unprocessable Content). Old names still work as deprecated aliases.
- Unofficial codes kept apart: 418, 419, 420, nginx 444 and 494-499, Cloudflare 520-527 and more live in
Unofficial, markedofficial: false. - Lookups both ways:
reason(404)andcode('not found'). Case and punctuation do not matter. Unknown values returnundefinedinstead of throwing. - Helper checks:
isRetryable,isRedirect,isEmptyBody,isCacheable, class checks such asisClientError, andinfo()with spec links and descriptions. HttpError: same shape as anhttp-errorserror.toJSON()gives problem details andtoResponse()gives a webResponse.- Small and tree-shakeable (your bundler drops what you do not import):
Statusalone is about 0.75 KB gzipped, everything is about 6.6 KB. - Zero dependencies, ESM and CommonJS, TypeScript types included.
Installation
npm install fourohfourpnpm add fourohfour
yarn add fourohfour
bun add fourohfourQuick start
import { Status, reason, code, isRetryable, HttpError } from 'fourohfour'
Status.NOT_FOUND // => 404
reason(404) // => 'Not Found'
reason(413) // => 'Content Too Large'
reason(413, { legacy: true }) // => 'Payload Too Large' (what Node.js says)
code('not found') // => 404
code('Unprocessable Entity') // => 422 (old names work)
isRetryable(503) // => true
const error = new HttpError(404, 'No user with id 42')
error.toJSON()
// => { type: 'about:blank', title: 'Not Found', status: 404, detail: 'No user with id 42' }With CommonJS:
const { Status } = require('fourohfour')Table of contents
Usage
Compare a status code with a constant
import { Status } from 'fourohfour'
if (res.status === Status.NO_CONTENT) return null
if (res.status === Status.NOT_FOUND) return undefinedHover a constant in your editor to see its phrase and the RFC that defines it.
Get the reason phrase for a code
import { reason } from 'fourohfour'
reason(404) // => 'Not Found'
reason('503') // => 'Service Unavailable'
reason(299) // => undefined
console.log(`${req.method} ${req.url} ${res.statusCode} ${reason(res.statusCode)}`)
// Prints: GET /users/42 404 Not FoundFind the code for a phrase or name
import { code } from 'fourohfour'
code('Not Found') // => 404
code('NOT_FOUND') // => 404
code('Gateway Time-out') // => 504
code('Nope') // => undefinedDecide what to do with a response
import { isRetryable, isEmptyBody } from 'fourohfour'
if (isRetryable(res.status)) await retryLater(res.headers.get('retry-after'))
if (isEmptyBody(status)) res.end()
else res.end(body)isRetryable is true for 408, 425, 429, 500, 502, 503 and 504. See Helper checks for the full list.
Throw an HTTP error
import { HttpError, createError } from 'fourohfour'
throw new HttpError(404) // message: 'Not Found'
throw new HttpError(404, 'No user with id 42')
throw new HttpError(429, { headers: { 'Retry-After': '60' } })
throw new HttpError(502, 'Payment provider failed', { cause: err })
throw createError(403, 'Admins only') // same as new HttpError(...)Send errors from an Express app
import { HttpError, isHttpError, PROBLEM_JSON } from 'fourohfour'
app.use((err, req, res, next) => {
const e = isHttpError(err) ? err : new HttpError(500, { cause: err })
res.status(e.status).set(e.headers).type(PROBLEM_JSON).json(e)
})res.json(e) calls e.toJSON(), so the client gets problem details.
Return errors from a fetch handler
toResponse() gives a web-standard Response. Use it in fetch handlers, edge functions, Bun, Deno and Hono.
import { HttpError, isHttpError } from 'fourohfour'
export default {
async fetch(req) {
try {
return await handle(req)
} catch (err) {
return (isHttpError(err) ? err : new HttpError(500, { cause: err })).toResponse()
}
},
}Keep internal error messages private
By default, toJSON() includes your message for 4xx errors and leaves it out for 5xx errors. This stops internal details from reaching the client.
import { HttpError, isRetryable, reason } from 'fourohfour'
new HttpError(500, 'SQL error near "users"').toJSON()
// => { type: 'about:blank', title: 'Internal Server Error', status: 500 }
// Report an upstream failure. Keep the details in `cause` for your logs.
const res = await fetch(url)
if (!res.ok) {
throw new HttpError(isRetryable(res.status) ? 503 : 502, {
cause: new Error(`${url}: ${res.status} ${reason(res.status) ?? ''}`),
})
}Accept only some status codes in TypeScript
import { Status } from 'fourohfour'
import type { SuccessStatus } from 'fourohfour'
function send(status: SuccessStatus, body: unknown) { /* ... */ }
send(Status.OK, data) // OK
send(Status.NOT_FOUND, data) // Type error: 404 is not a success statusList every status code
import { allCodes } from 'fourohfour'
allCodes() // => [100, 101, 102, 103, 200, ...] (61 official codes)
allCodes({ unofficial: true }) // => [100, 101, 102, 103, 104, 200, ...] (88 codes)Use allCodes() instead of Object.values(Status). Status has deprecated aliases, so some codes appear more than once in it.
API
All exports are named. There is no default export.
Status, Unofficial, Reason
const Status: { readonly CONTINUE: 100; readonly OK: 200; readonly NOT_FOUND: 404; /* ... */ }
const Unofficial: { readonly IM_A_TEAPOT: 418; readonly CLIENT_CLOSED_REQUEST: 499; /* ... */ }
const Reason: { readonly 200: 'OK'; readonly 404: 'Not Found'; /* ... */ }Statushas every IANA-registered code, named after its RFC 9110 reason phrase.Unofficialhas codes that are common but not registered.Reasonmaps every known code, official and unofficial, to its reason phrase.
import { Status, Unofficial, Reason } from 'fourohfour'
Status.OK // => 200
Status.UNPROCESSABLE_CONTENT // => 422
Status.UNPROCESSABLE_ENTITY // => 422 (deprecated alias)
Unofficial.CLIENT_CLOSED_REQUEST // => 499
Reason[404] // => 'Not Found'Deprecated aliases in Status are kept so old code still compiles. Editors show them struck through.
| Alias | Code | Use instead |
|---|---|---|
| MOVED_TEMPORARILY | 302 | FOUND |
| PAYLOAD_TOO_LARGE | 413 | CONTENT_TOO_LARGE |
| REQUEST_ENTITY_TOO_LARGE | 413 | CONTENT_TOO_LARGE |
| REQUEST_TOO_LONG | 413 | CONTENT_TOO_LARGE |
| REQUEST_URI_TOO_LONG | 414 | URI_TOO_LONG |
| REQUESTED_RANGE_NOT_SATISFIABLE | 416 | RANGE_NOT_SATISFIABLE |
| UNPROCESSABLE_ENTITY | 422 | UNPROCESSABLE_CONTENT |
| Code | Name | Source | |---|---|---| | 104 | Upload Resumption Supported | IETF draft (temporary IANA registration) | | 218 | This Is Fine | Apache | | 306 | Switch Proxy | Reserved by RFC 9110, unused | | 418 | I'm a Teapot | RFC 2324, reserved by RFC 9110 | | 419 | Page Expired | Laravel | | 420 | Enhance Your Calm | Twitter | | 440 | Login Time-out | Microsoft IIS | | 444 | No Response | nginx | | 449 | Retry With | Microsoft IIS | | 450 | Blocked by Windows Parental Controls | Microsoft | | 494 | Request Header Too Large | nginx | | 495 | SSL Certificate Error | nginx | | 496 | SSL Certificate Required | nginx | | 497 | HTTP Request Sent to HTTPS Port | nginx | | 498 | Invalid Token | Esri ArcGIS | | 499 | Client Closed Request | nginx | | 509 | Bandwidth Limit Exceeded | Apache, cPanel | | 520-527 | Unknown Error, Web Server Is Down, Connection Timed Out, Origin Is Unreachable, A Timeout Occurred, SSL Handshake Failed, Invalid SSL Certificate, Railgun Error | Cloudflare | | 598, 599 | Network Read / Connect Timeout Error | Proxy convention |
reason(code, options?)
function reason<C extends KnownStatusCode>(code: C, options?: { legacy?: false }): ReasonPhrase<C>
function reason(code: number | string, options?: ReasonOptions): string | undefinedReturns the reason phrase for a code. Accepts numbers and numeric strings. Returns undefined for unknown codes. With a literal code, the return type is the literal phrase: reason(404) has the type 'Not Found'.
| Option | Type | Default | Description |
|---|---|---|---|
| legacy | boolean | false | Return the older phrase that Node.js http.STATUS_CODES and statuses use. Only 413 (Payload Too Large) and 422 (Unprocessable Entity) differ from RFC 9110. |
reason(404) // => 'Not Found'
reason(499) // => 'Client Closed Request'
reason(422, { legacy: true }) // => 'Unprocessable Entity'code(phrase)
function code<P extends ReasonPhrase>(phrase: P): CodeOf<P>
function code(phrase: string): KnownStatusCode | undefinedReturns the code for a reason phrase or constant name. Case, spaces, hyphens, underscores and apostrophes are ignored. Old phrases and numeric strings also work. Returns undefined if nothing matches.
code('Not Found') // => 404
code("i'm a teapot") // => 418
code('Request Entity Too Large') // => 413
code('404') // => 404info(code)
function info<C extends KnownStatusCode>(code: C): StatusInfo<C>
function info(code: number | string): StatusInfo | undefinedReturns everything known about a code, or undefined for unknown codes.
info(413)
// => {
// code: 413,
// reason: 'Content Too Large',
// name: 'CONTENT_TOO_LARGE',
// category: 'client-error',
// official: true,
// deprecated: false,
// spec: 'RFC 9110, Section 15.5.14',
// url: 'https://www.rfc-editor.org/rfc/rfc9110#section-15.5.14',
// description: 'The request content is larger than the server is willing to process.',
// aliases: ['Payload Too Large', 'Request Entity Too Large'],
// retryable: false,
// cacheable: false,
// emptyBody: false,
// }
info(522).spec // => 'Cloudflare'
info(522).url // => undefined| Field | Type | Description |
|---|---|---|
| code | number | The code, for example 404. |
| reason | string | The reason phrase. |
| name | string | The constant name in Status or Unofficial, for example 'NOT_FOUND'. |
| category | Category | See category(). |
| official | boolean | true if registered with IANA. |
| deprecated | boolean | true for 305 Use Proxy, 510 Not Extended (obsolete) and 527 Railgun Error. |
| spec | string | Where the code is defined, for example 'RFC 9110, Section 15.5.5' or 'nginx'. |
| url | string \| undefined | Link to the definition, when a public spec exists. |
| description | string | One sentence about what the code means. |
| aliases | string[] | Older phrases for the same code. |
| retryable | boolean | Same as isRetryable(code). |
| cacheable | boolean | Same as isCacheable(code). |
| emptyBody | boolean | Same as isEmptyBody(code). |
info() holds all descriptions (about 5.5 KB gzipped). The other functions do not import them.
allCodes(options?)
function allCodes(options?: { unofficial?: false }): StatusCode[]
function allCodes(options: AllCodesOptions): KnownStatusCode[]Returns every official code, sorted from low to high.
| Option | Type | Default | Description |
|---|---|---|---|
| unofficial | boolean | false | Also include the codes in Unofficial. |
category(code)
const category: (code: unknown) => Category | undefined
type Category = 'informational' | 'success' | 'redirection' | 'client-error' | 'server-error'Returns the class of a code, from its first digit. Works for any integer from 100 to 599, known or not, and for numeric strings. Returns undefined for anything else.
category(404) // => 'client-error'
category('503') // => 'server-error'
category(299) // => 'success'
category(600) // => undefinedHelper checks
const isValid: (code: unknown) => code is number
const isKnown: (code: unknown) => code is KnownStatusCode
const isOfficial: (code: unknown) => code is StatusCode
const isRetryable: (code: unknown) => boolean // and the other checks belowEvery check returns false for anything that is not a status code (NaN, 404.5, null, ...). The class and behavior checks also accept numeric strings like '404'. The type guards (functions that also narrow the TypeScript type) isValid, isKnown and isOfficial accept numbers only.
| Function | Returns true for |
|---|---|
| isValid(code) | Any integer from 100 to 599 (the range RFC 9110 allows) |
| isKnown(code) | Codes in Status or Unofficial |
| isOfficial(code) | IANA-registered codes (in Status) |
| isInformational(code) | 1xx |
| isSuccess(code) | 2xx |
| isRedirection(code) | 3xx, including 304 |
| isClientError(code) | 4xx |
| isServerError(code) | 5xx |
| isError(code) | 4xx and 5xx |
| isRedirect(code) | 301, 302, 303, 307, 308: redirects to follow with the Location header (the Fetch standard's list) |
| isRedirectWithBody(code) | 307, 308: the client must repeat the same method and body (for 301 and 302 it may switch to GET, for 303 it must) |
| isRetryable(code) | 408, 425, 429, 500, 502, 503, 504 |
| isEmptyBody(code) | 1xx, 204, 205, 304: the response never has a body |
| isCacheable(code) | 200, 203, 204, 206, 300, 301, 308, 404, 405, 410, 414, 501: cacheable by default (RFC 9110 section 15.1) |
isValid narrows unknown to number. isKnown narrows to KnownStatusCode and isOfficial to StatusCode.
new HttpError(status, message?, options?)
class HttpError<S extends number = number> extends Error {
constructor(status: S, message?: string, options?: HttpErrorOptions)
constructor(status: S, options?: HttpErrorOptions)
}An error with an HTTP status code. status must be an integer from 400 to 599, otherwise a RangeError is thrown. The message defaults to the reason phrase, or 'Client Error' / 'Server Error' for unknown codes.
| Option | Type | Default | Description |
|---|---|---|---|
| cause | unknown | - | The original error, kept as error.cause. |
| headers | Record<string, string> | {} | Headers to send, such as Retry-After, Allow or WWW-Authenticate. |
| expose | boolean | true for 4xx, false for 5xx | Whether the message is safe to send to clients. When false, toJSON() leaves out detail. |
| type | string | 'about:blank' | RFC 9457 problem type (a URI). |
| title | string | The reason phrase | RFC 9457 title. |
| instance | string | - | RFC 9457 URI for this one occurrence. |
| extensions | Record<string, unknown> | {} | Extra fields for toJSON(). They cannot overwrite type, title, status, detail or instance. |
| Property | Description |
|---|---|
| status, statusCode | The status code. With a literal, typed as the literal: new HttpError(404).status has the type 404. |
| message | Your message, or the reason phrase. |
| expose | Whether message is safe to send to clients. |
| headers | Headers to send with the response. |
| cause | The cause option. |
| type, title, instance, extensions | RFC 9457 fields, from the options. |
It has the same shape as an http-errors error (status, statusCode, expose, headers), so Express and Koa error handling treat it like one.
createError(status, message?, options?)
function createError<S extends number>(status: S, message?: string, options?: HttpErrorOptions): HttpError<S>
function createError<S extends number>(status: S, options?: HttpErrorOptions): HttpError<S>Same as new HttpError(...).
error.toJSON()
toJSON(): ProblemDetailsReturns RFC 9457 problem details. detail is the message. It is included only when the error is exposed and the message is different from the title. JSON.stringify(error) uses toJSON().
new HttpError(404, 'No user with id 42').toJSON()
// => { type: 'about:blank', title: 'Not Found', status: 404, detail: 'No user with id 42' }
new HttpError(422, 'Invalid order', {
type: 'https://example.com/problems/validation',
title: 'Validation failed',
instance: '/orders/12',
extensions: { errors: [{ field: 'email', message: 'is required' }] },
}).toJSON()
// => {
// type: 'https://example.com/problems/validation',
// title: 'Validation failed',
// status: 422,
// detail: 'Invalid order',
// instance: '/orders/12',
// errors: [{ field: 'email', message: 'is required' }],
// }error.toResponse()
toResponse(): ResponseReturns a web-standard Response with the problem details as the body, the error's status, Content-Type: application/problem+json and the error's headers.
const res = new HttpError(429, { headers: { 'Retry-After': '60' } }).toResponse()
res.status // => 429
res.headers.get('content-type') // => 'application/problem+json'
res.headers.get('retry-after') // => '60'isHttpError(value)
const isHttpError: (value: unknown) => value is HttpErrorReturns true for an HttpError, also one created by a different copy of fourohfour (for example, when two versions are installed).
PROBLEM_JSON
const PROBLEM_JSON = 'application/problem+json'The media type for RFC 9457 problem details.
Types
import type {
StatusCode, // 100 | 101 | ... | 511 (official)
UnofficialStatusCode, // 104 | 218 | 306 | 418 | ... | 599
KnownStatusCode, // both
InformationalStatus, SuccessStatus, RedirectionStatus,
ClientErrorStatus, // 400 | 401 | ... | 451 (official 4xx)
ServerErrorStatus, // 500 | ... | 511
ErrorStatus, // ClientErrorStatus | ServerErrorStatus
ReasonPhrase, // ReasonPhrase<404> = 'Not Found'
CodeOf, // CodeOf<'Not Found'> = 404
StatusName, // 'OK' | 'NOT_FOUND' | ...
UnofficialStatusName, // 'IM_A_TEAPOT' | 'CLIENT_CLOSED_REQUEST' | ...
StatusInfo, Category, ReasonOptions, AllCodesOptions,
HttpErrorOptions, ProblemDetails,
} from 'fourohfour'Comparison
Checked against [email protected], [email protected] and [email protected].
| | http-status-codes | http-status | statuses | fourohfour |
|---|---|---|---|---|
| Constants | StatusCodes.NOT_FOUND (TS enum) | status.NOT_FOUND | No | Status.NOT_FOUND (literal type) |
| 413 / 422 phrase | Request Entity Too Large / Unprocessable Entity | Request Entity Too Large / Unprocessable Entity | Payload Too Large / Unprocessable Entity | Content Too Large / Unprocessable Content (RFC 9110), legacy on request |
| All IANA codes | No (missing 208, 226, 425, 506, 508, 510) | Yes | Yes | Yes |
| Unofficial codes | 418, 419, 420 mixed in, not marked | Yes, separate extra objects | 418, 509 mixed in | Yes, separate Unofficial, official: false |
| Phrase to code | Exact case only, throws | No | Yes, any case, throws | Yes, any case or punctuation, legacy names, constant names |
| Unknown code | Throws | undefined | Throws | undefined |
| Helper checks | No | No | redirect, empty, retry (502-504) maps | Class checks, isRetryable, isRedirect, isEmptyBody, isCacheable, ... |
| Spec links / descriptions | In JSDoc | Descriptions | No | info(): RFC section, URL, description, flags |
| Error class | No | No | No | HttpError with RFC 9457 toJSON() / toResponse() |
| Bundle for NOT_FOUND (min+gz, esbuild) | 2.8 KB | 7.5 KB | n/a | 0.75 KB |
| ESM / CommonJS | Yes / Yes | Yes / Yes | No / Yes | Yes / Yes |
| TypeScript types | Yes | Yes | @types/statuses | Yes, built in |
Migrating from other packages
From http-status-codes
// Before
import { StatusCodes, ReasonPhrases, getReasonPhrase, getStatusCode } from 'http-status-codes'
StatusCodes.NOT_FOUND
ReasonPhrases.NOT_FOUND
getReasonPhrase(404)
getStatusCode('Not Found')
// After
import { Status, Reason, reason, code } from 'fourohfour'
Status.NOT_FOUND
Reason[Status.NOT_FOUND]
reason(404)
code('Not Found')Differences:
- Lookups return
undefinedinstead of throwing. REQUEST_TOO_LONGandUNPROCESSABLE_ENTITYstill work but are marked deprecated.IM_A_TEAPOTisUnofficial.IM_A_TEAPOT.- 419 and 420 are Laravel's Page Expired and Twitter's Enhance Your Calm in
Unofficial, not Insufficient Space on Resource and Method Failure.
From http-status
| Before | After |
|---|---|
| status.NOT_FOUND | Status.NOT_FOUND |
| status[404] | reason(404) or Reason[404] |
| status['404_MESSAGE'] | info(404).description |
| status['404_CLASS'] | category(404) |
| status.extra.nginx[499] | reason(499) |
From statuses
| Before | After | Note |
|---|---|---|
| status(404) | reason(404, { legacy: true }) | Same phrases as statuses and Node.js |
| status('not found') | code('not found') | |
| status.redirect[n] | isRedirect(n) | statuses also lists 300 and 305 |
| status.empty[n] | isEmptyBody(n) | Also true for 1xx here |
| status.retry[n] | isRetryable(n) | Also true for 408, 425, 429 and 500 here |
From http-errors
// Before
import createError from 'http-errors'
// After
import { createError } from 'fourohfour'
throw createError(404, 'No user with id 42')createError(404, 'msg') works the same, and the error has status, statusCode, expose and headers. One difference: a status outside 400-599 throws a RangeError. http-errors prints a deprecation warning and keeps going.
Notes and limitations
- Lookups (
reason,code,info,category) returnundefinedfor unknown input. They never throw, so check the result. Statuscontains deprecated aliases, soObject.values(Status)has duplicate codes. UseallCodes()to list codes.- The type guards
isValid,isKnownandisOfficialreturnfalsefor strings, even'404'. The other checks accept numeric strings. HttpErroronly accepts 400 to 599. Other values throw aRangeError.- Some unofficial codes mean different things to different vendors. fourohfour uses the meanings in the
Unofficialtable above. info()adds about 5.5 KB gzipped because it holds all descriptions. Import it only if you need it.toResponse()needs a globalResponseclass. Node.js 20+, Bun, Deno, browsers and edge runtimes all have one.
Requirements
- Node.js 20 or newer. Also works in Bun, Deno, browsers and edge runtimes.
- ESM and CommonJS builds.
- TypeScript types included.
- Zero dependencies.
License
MIT
