http.STATUS_CODES

Maps every standard HTTP status code to its short reason phrase.

Signature
http.STATUS_CODES
  • Added in Node.js v0.1.22

Return value

<Object>An object whose keys are status codes as strings and whose values are the standard reason phrases, for example http.STATUS_CODES[404] === 'Not Found'.

Errors

Never throws — an unrecognised code simply yields undefined.

http.STATUS_CODES is a plain object, available the moment you require the module and needing no server or request. Keys are the numeric codes as strings; JavaScript coerces a number key on lookup, so STATUS_CODES[404] and STATUS_CODES['404'] are the same entry.

When to reach for it

Use it anywhere you would otherwise hard-code a reason phrase: building a plain-text or HTML error page, labelling a status in a log line or metrics dimension, or writing an error class that turns a code into a message. It saves shipping a status-code npm package for what is one property lookup.

What trips people up

  • Unknown codes return undefined, not a fallback string. Custom codes such as Cloudflare's 520 or an app-specific 499 are absent, so template a code straight into a page and you get Error: undefined. Guard with ?? 'Unknown Status'.
  • The set is not frozen. Nothing stops you assigning STATUS_CODES[599] = '...', and that mutation is process-wide — every module sharing the http instance sees it.
  • The contents vary by Node version as the IANA registry changes, so do not assert on Object.keys(...).length in a test.
  • Reason phrases are decorative. HTTP/2 dropped them entirely; clients route on the number.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Render a generic error page body from just the status code
  • Label a status code in a log line or a metrics dimension without a lookup table
  • Give an HttpError class a default message derived from its code
  • Check whether a numeric code is a registered standard one before returning it

Frequently asked questions

How do I get the status text for a code in Node?

Read http.STATUS_CODES[code] — for example http.STATUS_CODES[404] returns 'Not Found'. It is a plain object on the http module, so no server, request, or extra dependency is involved.

Why is http.STATUS_CODES returning undefined?

The code is not in the standard registry. The table covers only IANA-registered codes, so vendor-specific values like Cloudflare's 520–527 or nginx's 499 are missing. Use http.STATUS_CODES[code] ?? 'Unknown Status' wherever the code might not be standard.

Do I need a status-code npm package in Node?

Usually not — http.STATUS_CODES already maps every standard code to its reason phrase. A package is only worth it if you want named constants (StatusCodes.NOT_FOUND), reverse lookup from phrase to code, or coverage of non-standard vendor codes.

More examples

A generic error responder

One helper covers every error path because the reason phrase comes from the table rather than a hand-maintained switch. The ?? fallback matters: a service that later returns a vendor code such as 520 would otherwise emit {"error":null} and a status line ending in "undefined".

Example · javascript
const http = require('node:http');

function sendError(res, code, detail) {
  // Fall back for unregistered codes so the page never says "undefined".
  const phrase = http.STATUS_CODES[code] ?? 'Unknown Status';
  const body = JSON.stringify({
    error: phrase,
    status: code,
    ...(detail ? { detail } : {}),
  });

  res.writeHead(code, phrase, {
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(body),
  }).end(body);
}

const server = http.createServer((req, res) => {
  if (req.method !== 'GET') return sendError(res, 405, `${req.method} not allowed`);
  if (req.url !== '/') return sendError(res, 404);
  res.writeHead(200, { 'Content-Type': 'text/plain' }).end('ok\n');
});

server.listen(3000);

Classifying a code without hard-coded strings

Object.hasOwn() distinguishes a registered code from one the table does not know, which is more reliable than checking for undefined if anything in the process has mutated the object. The 520 line is the practical case: Cloudflare and other intermediaries return codes that are perfectly valid on the wire but absent from IANA's registry, and therefore from this table.

Example · javascript
const http = require('node:http');

function describe(code) {
  const known = Object.hasOwn(http.STATUS_CODES, String(code));
  const klass = Math.floor(code / 100);
  const family = {
    1: 'informational', 2: 'success', 3: 'redirection',
    4: 'client error', 5: 'server error',
  }[klass] ?? 'invalid';

  return `${code} ${http.STATUS_CODES[code] ?? '(unregistered)'} - ${family}${known ? '' : ', not in the registry'}`;
}

for (const code of [103, 204, 308, 429, 451, 503, 520]) {
  console.log(describe(code));
}
// 103 Early Hints - informational
// 204 No Content - success
// 308 Permanent Redirect - redirection
// 429 Too Many Requests - client error
// 451 Unavailable For Legal Reasons - client error
// 503 Service Unavailable - server error
// 520 (unregistered) - server error, not in the registry

Discussion

  • Be the first to comment on this lesson.