Loading

Fact dictionary

APIs

78 facts from 7 lessons of APIs. Each one names its source and leads back to its place in the lesson.

Lesson 1: HTTP and REST

India's own stack of APIs

Some APIs serve a whole country. India Stack, in its own words, is a set of open APIs and digital public goods for identity, data and payments at population scale. Wikipedia lists what it covers: identity checks with Aadhaar, payments with UPI and document storage with DigiLocker. It also reports a Financial Times article of 2023 that questioned how open those APIs are.

Why it fits here: It answers this topic's question: India Stack is a set of APIs for identity, data and payments, under Aadhaar, UPI and DigiLocker.

Sources: India Stack; Wikipedia: India Stack

Topic: APIs: programs that answer programs · internet, history

A promise that Linux keeps

Linux treats its interface to programs as a promise. The kernel's own documentation states a no regressions rule: if an application ran fine with one kernel, a newer kernel must not make it work worse, or not at all. A developer who breaks one by accident is expected to fix it quickly. Within that rule, even its APIs may change, as long as no existing application breaks.

Why it fits here: It shows this topic's promise kept at scale: Linux forbids a change that breaks a program which ran before.

Source: The Linux kernel documentation: Reporting regressions

Topic: APIs: programs that answer programs · standards, tools

Pages of at most 100

Big collections come in pages. GitHub's documentation for its REST API says that, for most endpoints, the query parameter per_page can ask for at most 100 results on a page. A bigger number gives no error: GitHub lowers it to the maximum. The link header of each answer gives the addresses of the other pages.

Why it fits here: It answers this topic's question: GitHub pages its collections, at most 100 items at a time, with links to the other pages.

Source: GitHub Docs: Using pagination in the REST API

Topic: Resources and their addresses · tools, numbers

REST's author helped write HTTP

The man who named REST helped write HTTP itself. Roy Fielding's name stands first among the authors of HTTP/1.1, in RFC 2068 of January 1997 and RFC 2616 of June 1999, and he was an editor of RFC 9110, the HTTP standard of June 2022. His dissertation of 2000 says that since 1994 the REST style had guided the design of the modern Web.

Why it fits here: It adds to this topic's REST: Roy Fielding, who named it in 2000, also wrote the HTTP standards themselves.

Sources: RFC 2068: Hypertext Transfer Protocol, HTTP/1.1; RFC 2616: Hypertext Transfer Protocol, HTTP/1.1; RFC 9110: HTTP Semantics; Roy Fielding: Architectural Styles and the Design of Network-based Software Architectures; Roy Fielding's dissertation, chapter 6: Experience and Evaluation

Topic: Resources and their addresses · people, history

Forms know two methods

A plain HTML form cannot send PUT, PATCH or DELETE. The HTML standard gives a form's method attribute three keywords: get, post and dialog, and dialog sends nothing at all, as it closes the dialog box that holds the form. A missing or unknown method means GET. So a page that deletes through a REST API does it with JavaScript, such as fetch.

Why it fits here: It answers this topic's question: an HTML form sends only GET or POST, so PUT, PATCH and DELETE need JavaScript.

Source: HTML Standard: Form submission attributes

Topic: Methods: what to do with a resource · browsers, standards

PATCH came last

PATCH is the youngest of the five. RFC 5789, by Lisa Dusseault and James Snell, added it to HTTP in March 2010. Its reason, in its own words: applications needed partial modification of a resource, while the existing PUT method only allows a complete replacement of a document. So for changing one field, HTTP had no method of its own before 2010.

Why it fits here: It dates this topic's PATCH: it joined HTTP in 2010, to change part of a resource, while PUT replaces all of it.

Source: RFC 5789: PATCH Method for HTTP

Topic: Methods: what to do with a resource · history, standards

402, reserved since 1997

One code has waited for decades. The first standard for HTTP/1.1, RFC 2068 of January 1997, listed 402 Payment Required and said that it was reserved for future use. RFC 9110, the HTTP standard of June 2022, still says that 402 is reserved for future use. So no standard yet says what a 402 answer means.

Why it fits here: It answers this topic's question: 402 Payment Required has been reserved for future use since 1997, and still is.

Sources: RFC 2068: Hypertext Transfer Protocol, HTTP/1.1; RFC 9110: HTTP Semantics

Topic: Status codes in an API · history, numbers

429, for too many requests

An API can tell a client to slow down. RFC 6585, of April 2012, added the code 429 Too Many Requests. It means that the client has sent too many requests in a given amount of time, which the standard calls rate limiting, and the answer should explain the condition. An API that limits how often each key may ask answers with it.

Why it fits here: It adds to this topic's codes: 429 Too Many Requests, from 2012, tells a client that it is asking too often.

Source: RFC 6585: Additional HTTP Status Codes

Topic: Status codes in an API · internet, standards

The price of standing alone

Statelessness has a cost, and REST's author named it. Roy Fielding's dissertation calls the stateless rule a design trade-off: since nothing can be left on the server in a shared context, the same data is sent again with every request, which may decrease network performance. The gain is that a server stores nothing between requests, so it can free its resources quickly.

Why it fits here: It answers this topic's question: stateless requests resend the same data, the price of a server that remembers nothing.

Source: Roy Fielding's dissertation, chapter 5: Representational State Transfer (REST)

Topic: Every request stands alone · internet, standards

A key that works for whoever holds it

The key in a header has a standard form. RFC 6750, of October 2012, defines the bearer token, sent as Authorization: Bearer followed by the token. Any party that holds one can use it, the standard says, without proving anything more, much like cash. So a bearer token must be protected from disclosure, both where it is stored and while it travels.

Why it fits here: It names this topic's key in a header: a bearer token, sent as Authorization: Bearer, which works for whoever holds it.

Source: RFC 6750: The OAuth 2.0 Authorization Framework: Bearer Token Usage

Topic: Every request stands alone · privacy, standards

GitHub's versions have dates

GitHub names the versions of its REST API by date. Its documentation says that a client chooses one with the header X-GitHub-Api-Version, and that a request without it gets the version 2022-11-28. When a new version comes out, the one before it is supported for at least 24 more months. Breaking changes come only in a new version.

Why it fits here: It answers this topic's question: GitHub dates its versions and keeps the one before for at least 24 months.

Source: GitHub Docs: API Versions

Topic: Designing an API · tools, numbers

Hyrum's Law

Every visible habit of an API becomes part of its promise. Hyrum's Law says it this way: with a sufficient number of users of an API, it does not matter what you promise in the contract, as all observable behaviors of your system will be depended on by somebody. Its site calls the result bug-for-bug compatibility.

Why it fits here: It warns this topic's designer: once many clients use an API, even its habits that no table lists cannot change safely.

Source: Hyrum's Law

Topic: Designing an API · words, mistakes

Lesson 2: JSON

Each parser sets its own limits

The JSON standard sets no size limits of its own. RFC 8259 says that an implementation may set limits on the size of the texts it accepts, on the maximum depth of nesting, on the range and precision of numbers, and on the length and contents of strings. So a JSON text that one program reads may be refused by another.

Why it fits here: It answers this topic's question: the standard leaves limits on depth, size and numbers to each parser, so they differ.

Source: RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format

Topic: The JSON format · standards, numbers

Not quite a subset, until 2019

For years, JSON was not quite a part of JavaScript. The TC39 proposal JSON superset explains why: JSON strings could hold two invisible characters unescaped, U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR, while JavaScript strings could not. The proposal extended JavaScript into a superset of JSON, and it was scheduled for ES2019.

Why it fits here: It sharpens this topic's format: until ES2019, two characters made some JSON texts invalid JavaScript.

Source: TC39 proposal: Subsume JSON

Topic: The JSON format · languages, standards

JSON.rawJSON keeps every digit

A big number can now travel whole. JSON.rawJSON makes an object that holds a piece of JSON text, and JSON.stringify writes that text exactly as it is. So JSON.stringify({ id: JSON.rawJSON("12345678901234567890") }) keeps all twenty digits, which a JavaScript number would round. MDN marks it Baseline 2025: it works in the latest browsers since March 2025.

Why it fits here: It answers this topic's question: with JSON.rawJSON, JSON.stringify writes a long number digit for digit.

Sources: MDN: JSON.rawJSON(); TC39 proposal: JSON.parse source text access

Topic: JSON.stringify in depth · languages, numbers

Lone surrogates come out escaped

JSON.stringify once could produce text that UTF-8 cannot carry. A lone surrogate, a code unit from U+D800 to U+DFFF without its partner, was written out as it was. The TC39 proposal Well-formed JSON.stringify fixed this, and MDN says that engines with the fix write such a character as an escape sequence instead, so JSON.stringify("\uD800") gives "\ud800".

Why it fits here: It adds to this topic's JSON.stringify: a lone surrogate now comes out as an escape, so the text is valid UTF-8.

Sources: MDN: JSON.stringify(); TC39 proposal: Well-formed JSON.stringify

Topic: JSON.stringify in depth · languages, standards

X sends its ids as text

A large API follows the rule for ids. X's developer documentation says to always use string ids, because some languages, like JavaScript, cannot accurately represent 64-bit integers: JavaScript's integers are limited to 53 bits. So version 2 of its API returns ids as strings by default, and version 1.1 gave each id twice, as id, a number, and id_str, a string.

Why it fits here: It answers this topic's question: X sends its 64-bit ids as strings, as JavaScript's numbers are exact only to 53 bits.

Source: X Developer Platform: X IDs

Topic: JSON.parse in depth · numbers, tools

A reviver that sees the digits

A reviver can now see the text that a value came from. MDN describes a third argument for the reviver, context, whose source field holds the original JSON text of a primitive value. So a reviver can build a BigInt from a long number's own digits, before any rounding happens. The TC39 proposal behind it, JSON.parse source text access, has reached stage 4.

Why it fits here: It adds to this topic's reviver: its third argument holds a number's original digits, so a long id need not lose any.

Sources: MDN: JSON.parse(); TC39 proposal: JSON.parse source text access

Topic: JSON.parse in depth · languages, numbers

No charset for JSON

A JSON body needs no charset. RFC 8259 says that JSON text exchanged between systems that are not part of a closed ecosystem must be encoded in UTF-8. It defines no charset parameter for application/json: adding one really has no effect on a recipient that follows the standard. It also forbids a byte order mark at the start of JSON sent over a network.

Why it fits here: It answers this topic's question: JSON between systems is always UTF-8, so application/json has no charset to set.

Source: RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format

Topic: JSON over HTTP · standards, internet

The label from 2006

The label application/json comes from RFC 4627, of July 2006, written by Douglas Crockford, which says that the MIME media type for JSON text is application/json. That RFC is now obsolete: RFC 7159 replaced it, and RFC 8259 of December 2017 replaced that in turn. The label stayed the same through all three, so old clients and new ones still agree.

Why it fits here: It dates this topic's label: application/json was registered in 2006 and has not changed since.

Sources: RFC 4627: The application/json Media Type for JavaScript Object Notation (JSON); RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format

Topic: JSON over HTTP · history, standards

Date.parse is sure of one format

Date.parse is reliable for only one kind of text. MDN says it must support the date time string format that toISOString produces, while other formats are implementation-defined and may not work across all browsers. MDN even names the unreliability of Date.parse as one reason for the new Temporal API. So an API asks for ISO text, and nothing else.

Why it fits here: It answers this topic's question: only ISO text is sure to parse the same everywhere, so APIs accept dates in it alone.

Sources: MDN: Date.parse(); ECMAScript Language Specification: Date.parse

Topic: Checking a body · languages, mistakes

Checks written as data

Checks like these can be written as data instead of code. JSON Schema describes itself as a declarative language for defining structure and constraints for JSON data: a schema such as { "type": "number" } says what a value must be, and a validator checks a body against it. Its site says it is supported by many languages, libraries and frameworks.

Why it fits here: It adds to this topic's checks: JSON Schema writes them down as data, which validators in many languages can apply.

Sources: JSON Schema: What is JSON Schema?; JSON Schema

Topic: Checking a body · tools, standards

INR, 356 and 2

The rupee has an international code. In the list of ISO 4217, the standard for currencies, India's rupee is INR, with the number 356 and 2 digits after the decimal point, which is why money can travel as whole paise. Wikipedia explains the letters: IN is India's two-letter country code, and R is the initial of the currency. The same list shows Bhutan using INR too.

Why it fits here: It answers this topic's question: the rupee is INR, number 356, with 2 decimal digits, so 100 paise make a rupee.

Sources: SIX: ISO 4217 currency code list; Wikipedia: ISO 4217

Topic: Shapes of data that age well · numbers, standards

The Tolerant Reader

Martin Fowler named a habit that keeps clients alive when shapes grow: the Tolerant Reader, in May 2011. His advice is to be as tolerant as possible when reading data from a service: take only the parts you need and ignore the rest. Then a new field, which he says should not be a breaking change for anyone, breaks no reader.

Why it fits here: It adds the client's side of this topic's shapes: a reader that ignores unknown fields survives a shape that grows.

Source: Martin Fowler: Tolerant Reader

Topic: Shapes of data that age well · people, mistakes

Lesson 3: Express routing

Ten years to Express 5

Express 5 took ten years. The Express blog of October 15, 2024 says that its release pull request was opened in July 2014, and only then merged and published. It thanks Doug Wilson above all, who spent those ten years keeping Express the most stable project around. Express 4 had come out in April 2014, so it served for a decade.

Why it fits here: It answers this topic's question: Express 5 was opened in July 2014 and published in 2024, ten years later.

Sources: Express blog: Introducing Express v5; npm registry: express

Topic: The first app · history, tools

Inspired by Sinatra

Express has been around since 2010. Its version 1.0.0 was tagged by TJ Holowaychuk in November 2010, and its early npm entries describe it as a Sinatra inspired web development framework. Sinatra is a small web framework written in Ruby. From it, Wikipedia says, Express took a design that stays minimal, with many features available as plugins.

Why it fits here: It dates this topic's Express: version 1.0.0 came in 2010, modelled on Ruby's small framework Sinatra.

Sources: GitHub: Express release 1.0.0; npm registry: express 1.0.0; Wikipedia: Express.js; Wikipedia: Sinatra (software)

Topic: The first app · history, people

QUERY, the newest method

HTTP gained a method in June 2026. RFC 10008 defines QUERY: like POST, it carries content, such as a search, but like GET it is safe and idempotent, so it can be repeated or restarted without any harm. Express's documentation already gives app.query an entry of its own, beside app.get, app.post, app.put and app.delete.

Why it fits here: It answers this topic's question: QUERY, from RFC 10008 of June 2026, is a safe search that carries a body.

Sources: IETF Datatracker: The HTTP QUERY Method; RFC 10008: The HTTP QUERY Method; Express 5.x API: Application

Topic: Routes: a verb and a path · standards, internet

Two settings make paths strict

Express can be made strict about paths. Its documentation lists two settings that are off unless set. With case sensitive routing, /Foo and /foo are different routes; with strict routing, /foo and /foo/ are different. Each is read when the app first creates its router, which adding a route already does, so it must be set before any route.

Why it fits here: It adds to this topic's string paths: two settings make capitals and a final slash count, if set before the first route.

Source: Express 5.x API: Application (settings)

Topic: Routes: a verb and a path · tools, mistakes

No patterns inside string paths

Express 5 refuses a pattern inside a string path, such as /:foo(\d+), which Express 4 accepted. The Express blog explains why: it is easy to write a regular expression that takes exponential time on some input, the attack called regular expression denial of service, or ReDoS. A last-minute change to the path rules removed that possibility.

Why it fits here: It answers this topic's question: patterns inside string paths were dropped to stop ReDoS attacks.

Source: Express blog: Introducing Express v5

Topic: Names inside the path · mistakes, tools

One callback per parameter

A parameter can have code of its own. With app.param("id", callback), the callback for id runs before any handler of any route that holds it. The Express documentation adds that it runs only once in a request, even if the parameter is matched in several routes. So one place can load the item that an id names.

Why it fits here: It adds to this topic's parameters: app.param runs one callback for a parameter, once per request, before the handlers.

Source: Express 5.x API: Application (app.param)

Topic: Names inside the path · tools, tricks

Express 5 reads queries the plain way

Express 5 changed how it reads a query. Its migration guide says that the default query parser changed from extended to simple. The simple one is Node's own querystring. The extended one is the package qs, which builds nested objects from names in square brackets, so foo[bar]=baz became an object inside an object. A setting brings the old way back.

Why it fits here: It answers this topic's question: Express 4 read queries with qs, nested objects and all, and Express 5 with Node's querystring.

Sources: Express: Migrating to Express 5; Express 5.x API: Application (settings); qs on GitHub

Topic: The query string, and the rest of the request · tools, history

Faster, or standard

Node has two readers of query strings, and its manual compares them. The querystring module is more performant than URLSearchParams, it says, but it is not a standardized API. So the manual advises URLSearchParams when speed is not critical, or when the code must also run in a browser, where URLSearchParams exists as well.

Why it fits here: It adds to this topic's query: Node's querystring is faster, while URLSearchParams is the standard one that browsers share.

Source: Node.js manual: Query string

Topic: The query string, and the rest of the request · tools, standards

Redirects that keep the method

A redirect can change the method. RFC 9110 notes that, for historical reasons, a client may change a POST into a GET when it follows a 301 or a 302. To keep the method, a server answers 307 Temporary Redirect or 308 Permanent Redirect instead. The code 308 became a standard with RFC 7538 of April 2015, which replaced RFC 7238.

Why it fits here: It answers this topic's question: after 301 or 302 a POST may become a GET, while 307 and 308 keep it a POST.

Sources: RFC 9110: HTTP Semantics; RFC 7538: The Hypertext Transfer Protocol Status Code 308 (Permanent Redirect)

Topic: Sending the answer · standards, history

Escaped JSON, on request

Express can write its JSON more cautiously. Its setting json escape, off unless set, makes res.json and res.send write the characters <, > and & as Unicode escape sequences. The documentation says the purpose is to help against certain persistent XSS attacks, when clients sniff a response for HTML; the escaped text still reads as the same JSON.

Why it fits here: It adds to this topic's res.json: one setting escapes <, > and &, against attacks that treat JSON as HTML.

Source: Express 5.x API: Application (settings)

Topic: Sending the answer · privacy, tools

A router of its own

Express does not do its routing alone. Its package.json, at version 5.3.0, lists router among its dependencies: a separate package, which its project describes as a simple middleware-style router. Its README says that it was extracted from the Express project, and its example runs it on a plain Node server, with no Express at all.

Why it fits here: It answers this topic's question: Express's routing comes from router, a package of its own that Express depends on.

Sources: Express on GitHub: package.json; router on GitHub

Topic: Routers: routes in groups · tools, standards

app.router came back

One name left Express and returned. The Express 5 migration guide says that the app.router object, removed in Express 4, has made a comeback in Express 5. Now it is a reference to the app's own base router, created on first access, while in Express 3 an app had to load it explicitly.

Why it fits here: It adds to this topic's routers: every app has a built-in router, reachable again as app.router since Express 5.

Sources: Express: Migrating to Express 5; Express 5.x API: Application (app.router)

Topic: Routers: routes in groups · history, tools

Lesson 4: Middleware

Middleware from Connect

Express's middleware has a parent. Connect, in its own words an extensible HTTP server framework for Node, called its plugins middleware, and earlier versions of Express were built on it. Express 4 cut the tie: its migration guide says that it no longer depends on Connect, and that it removed all built-in middleware from its core, except express.static.

Why it fits here: It answers this topic's question: the name and the idea came to Express from Connect, which Express 4 left behind.

Sources: Connect on GitHub; Express: Moving to Express 4

Topic: What middleware is · history, tools

Koa, from the same team

Express's own team built a second framework. Koa's site says that it was designed by the team behind Express, to be a smaller, more expressive and more robust foundation for web applications and APIs. Its middleware are async functions that cascade: when there is nothing left to run downstream, the stack unwinds, and each middleware resumes for its upstream work.

Why it fits here: It shows another shape of this topic's line: Koa's middleware, from Express's own team, run down the line and back up.

Source: Koa

Topic: What middleware is · tools, history

One log line for every server

Many web servers write their log lines in one shape. The documentation of W3C httpd says that every server used to have its own logfile format, which made general statistics collectors hard to write. So it brought in a common logfile format: remotehost rfc931 authuser [date] "request" status bytes. The logger morgan still writes it, as Standard Apache common log output.

Why it fits here: It answers this topic's question: servers share the common logfile format, made so that one tool could read every log.

Sources: W3C httpd: Logging Control; morgan on GitHub

Topic: A logger, and middleware on one route · history, internet

A logger named after Dexter

The logger kept by the Express project has a curious name. The README of morgan, an HTTP request logger middleware for Node, says that it is named after Dexter, a show you should not watch until completion. Like the logger of this topic, it waits for the answer, then writes one line per request.

Why it fits here: It adds to this topic's logger: morgan, the logger kept by the Express project, is named after the TV show Dexter.

Source: morgan on GitHub

Topic: A logger, and middleware on one route · words, tools

A 401 must say how to log in

A 401 answer has a duty. RFC 9110 says that 401 Unauthorized means the request lacks valid authentication credentials, and that a server sending it must send a WWW-Authenticate header with at least one challenge, which tells the client how to prove who it is. A client whose credentials are known but not enough gets 403 Forbidden instead.

Why it fits here: It answers this topic's question: a 401 must carry WWW-Authenticate, while 403 is for credentials that are not enough.

Source: RFC 9110: HTTP Semantics

Topic: Guards, and passing data along · standards, privacy

Comparing keys in constant time

Comparing a secret key needs care. Node's manual says that crypto.timingSafeEqual compares bytes with a constant-time algorithm, which does not leak timing information that would let an attacker guess one of the values. It suits secrets such as authentication cookies. An error is thrown when the two have different byte lengths, so a guard checks the lengths first.

Why it fits here: It sharpens this topic's key check: crypto.timingSafeEqual compares secrets without leaking clues through timing.

Source: Node.js manual: Crypto (crypto.timingSafeEqual)

Topic: Guards, and passing data along · privacy, tools

Bodies that must stay raw

Some bodies must not be parsed at all. Stripe signs the webhooks it sends to an API, and its documentation says that it needs the raw body of the request to verify the signature. Any change to the raw body makes the check fail, even one made by a framework that parses it. So such a route reads its body with express.raw(), as bytes.

Why it fits here: It answers this topic's question: a signed webhook's body must stay raw, so express.raw() reads it as bytes.

Source: Stripe Docs: Webhooks

Topic: Reading the body · tools, privacy

Files need multipart

HTML forms have three encodings. The HTML standard lists application/x-www-form-urlencoded, the default, then multipart/form-data and text/plain, and MDN says to use multipart/form-data when a form holds a file input. Express's own readers do not read it. The Express project keeps a separate middleware, multer, which handles multipart/form-data, mainly for uploading files.

Why it fits here: It adds to this topic's readers: a form with files sends multipart/form-data, which multer reads.

Sources: HTML Standard: Form submission attributes; MDN: The form element; multer on GitHub

Topic: Reading the body · browsers, tools

Dot files stay hidden

Express 5 hides files whose names begin with a dot. Its migration guide says that express.static's dotfiles option now defaults to ignore, while Express 4 served them. So a folder such as .well-known answers 404, which can break Android App Links and Apple Universal Links. The option dotfiles: "allow" serves such a folder on purpose.

Why it fits here: It answers this topic's question: since Express 5, dot files are ignored unless dotfiles allows them.

Source: Express: Migrating to Express 5

Topic: Serving files · tools, mistakes

Where the types come from

express.static does not choose types by itself. Express depends on serve-static, which sends files with the package send, which uses mime-types, which reads mime-db. That database calls itself a large database of mime types in a single public JSON file, gathered from IANA, Apache and nginx. A type registered with IANA is pulled in automatically.

Why it fits here: It adds to this topic's types: the extension is looked up in mime-db, a list gathered from IANA, Apache and nginx.

Sources: Express on GitHub: package.json; serve-static on GitHub: package.json; send on GitHub: package.json; mime-types on GitHub: package.json; mime-db on GitHub

Topic: Serving files · tools, standards

Express counts the parameters

Express tells an error handler apart by counting its parameters. The router's own code checks fn.length: a function whose length is not 4 is not a standard error handler, and errors pass it by. MDN explains a trap: length counts only the parameters before the first one with a default value, so (err, req, res, next = f) has a length of 3.

Why it fits here: It answers this topic's question: Express reads fn.length, so an error handler needs four plain parameters.

Sources: router on GitHub: lib/layer.js; MDN: Function: length

Topic: The end of the line: a 404 and an error handler · languages, mistakes

A 404 is not an error

Express does not treat a missing route as an error. Its FAQ says that 404 responses are not the result of an error, so the error-handling middleware will not capture them. A 404 means only that Express has run every middleware function and route and found that none of them answered. That is why the 404 middleware is an ordinary one.

Why it fits here: It explains this topic's order: a 404 is not an error to Express, so an ordinary middleware after the routes must answer it.

Source: Express FAQ

Topic: The end of the line: a 404 and an error handler · tools, mistakes

Lesson 5: Requests and responses

The X- prefix, retired

Made-up headers often start with X-, such as X-Yard. That habit was retired in June 2012. RFC 6648 says that the convention causes more problems than it solves, and deprecates it for new names. Its analysis gives the main problem: unstandardized names tend to leak into the standards, and then must migrate from the X- name to a standard one.

Why it fits here: It answers this topic's question: since RFC 6648 of 2012, new header names should not start with X-.

Source: RFC 6648: Deprecating the X- Prefix and Similar Constructs in Application Protocols

Topic: Headers in both directions · standards, history

Headers after the body

Not every header comes first. HTTP allows a trailer section after the body, and RFC 9110 calls its fields trailer fields, or trailers. It says that they can carry message integrity checks, digital signatures, delivery metrics or post-processing status, things that a sender may know only once the whole body has gone.

Why it fits here: It adds to this topic's headers: trailers are headers sent after the body, for facts known only at the end.

Source: RFC 9110: HTTP Semantics

Topic: Headers in both directions · standards, internet

406, or something useful

A server need not answer 406. RFC 9110 says that when none of the available forms is acceptable, the origin server can either honor the header by sending 406 Not Acceptable, or disregard it and answer as if no negotiation had been asked for. A default in res.format makes the second choice: a form the client did not list, rather than nothing.

Why it fits here: It answers this topic's question: the standard lets a server skip 406 and send a form the client did not ask for.

Source: RFC 9110: HTTP Semantics

Topic: One address, several forms · standards, tools

The rules of q

The weight q has firm rules. RFC 9110 says it runs from 0 to 1, where 0.001 is the least preferred and 1 the most, and that q=0 means not acceptable at all. A type with no q has the weight 1. Its grammar allows at most three digits after the point, so q=0.0001 is not a weight at all.

Why it fits here: It sharpens this topic's q: weights run from 0 to 1 with three decimals at most, and q=0 refuses a type.

Source: RFC 9110: HTTP Semantics

Topic: One address, several forms · standards, numbers

Names that carry a promise

A cookie's name can carry a promise. Under the draft revision of the cookie standard, a cookie whose name begins with __Host- is accepted only if it was set with Secure, with Path=/ and with no Domain. MDN explains the gain: such a cookie is sent only to the host that set it, never to other hosts of the same domain.

Why it fits here: It answers this topic's question: a name that begins with __Host- promises Secure, Path=/ and no Domain.

Sources: IETF draft: Cookies: HTTP State Management Mechanism (rfc6265bis); IETF Datatracker: draft-ietf-httpbis-rfc6265bis; MDN: Set-Cookie

Topic: Cookies: a note the client brings back · privacy, standards

Max-Age wins

A cookie may carry both an age and a date. RFC 6265 says that if a cookie has both Max-Age and Expires, Max-Age has precedence and controls when it expires. A cookie with neither is kept until the current session is over, as the browser defines it, which usually means until the browser closes.

Why it fits here: It adds to this topic's options: when Max-Age and Expires disagree, Max-Age decides.

Source: RFC 6265: HTTP State Management Mechanism

Topic: Cookies: a note the client brings back · standards, tools

Names in any script

A download's name can be in any script, such as a receipt named in Hindi. A name outside ISO-8859-1 travels in the parameter filename*, as RFC 6266 of June 2011 shows: filename*=UTF-8''%e2%82%ac%20rates names a file with a euro sign, in UTF-8 and percent codes. Express's content-disposition package handles such Unicode names by itself.

Why it fits here: It answers this topic's question: a name in Hindi travels as filename*, in UTF-8, which Express writes for you.

Sources: RFC 6266: Use of the Content-Disposition Header Field in HTTP; Express on GitHub: package.json; content-disposition on GitHub

Topic: Files and downloads · standards, words

An attack with a name

Climbing out with .. is an old attack with a name. OWASP calls it path traversal, or directory traversal: by using dot-dot-slash (../) sequences, or absolute paths, an attacker may reach files outside the web root, even the application's source code. The 403 that res.sendFile gives with root is a guard against exactly this.

Why it fits here: It names this topic's 403: a name with .. is a path traversal attack, which root stops.

Sources: OWASP: Path Traversal; PortSwigger Web Security Academy: Path traversal

Topic: Files and downloads · privacy, mistakes

Files that never change

Some files never change at their address, such as a script whose name holds a fingerprint of its contents. RFC 8246, of September 2017, gave them the Cache-Control extension immutable: the response will not be updated while it is fresh. So a client should not ask again during that time, not even on a reload, unless the person forces one.

Why it fits here: It answers this topic's question: Cache-Control: immutable tells a client not to check a fresh answer, even on a reload.

Source: RFC 8246: HTTP Immutable Responses

Topic: Answers the client already has · standards, internet

Two lifetimes in one answer

One answer can carry two lifetimes. RFC 9111 says that s-maxage applies only to shared caches, which keep answers for more than one user, and that there it overrides both max-age and Expires. So Cache-Control: max-age=60, s-maxage=3600 lets each browser keep the answer for a minute, and a shared cache for an hour.

Why it fits here: It adds to this topic's Cache-Control: s-maxage sets a separate lifetime for caches shared by many users.

Source: RFC 9111: HTTP Caching

Topic: Answers the client already has · standards, numbers

Lesson 6: Error handling

Errors that help an attacker

Error pages can help an attacker. OWASP's cheat sheet on error handling says that an attack begins with reconnaissance, a search for technical details such as the server, frameworks and libraries, and that unhandled errors can help in this first phase. Express's security guide calls it fingerprinting, and says that making it harder improves an app's overall security.

Why it fits here: It answers this topic's question: a stack trace tells an attacker what a server runs, so production hides it.

Sources: OWASP Cheat Sheet Series: Error Handling; Express: Security best practices

Topic: Where every error lands · privacy, mistakes

Production runs faster too

One setting changes more than error pages. Express's performance guide says that setting NODE_ENV to production makes Express cache view templates and the CSS built from CSS extensions, and generate less verbose error messages. It adds that tests indicate this alone can improve an app's performance by a factor of three.

Why it fits here: It adds to this topic's production mode: NODE_ENV=production hides stacks and, by Express's tests, can make an app three times faster.

Source: Express: Performance best practices

Topic: Where every error lands · tools, numbers

No made-up status codes

An API cannot invent a status code of its own. IANA keeps the registry of HTTP status codes, and RFC 9110 says that new values require IETF Review, so a new code needs the agreement of the IETF. That is why an API puts its own detail in a code inside the body, such as GAUGE_NOT_FOUND, and keeps to the standard statuses.

Why it fits here: It answers this topic's question: new HTTP statuses need IETF Review, so an API's own detail goes in the body's code.

Sources: RFC 9110: HTTP Semantics; IANA: HTTP Status Codes

Topic: One shape for every error · standards, internet

Problem Details, since 2016

The shape of this lesson's answers has a standard older than it seems. RFC 7807, Problem Details for HTTP APIs, came in March 2016, and RFC 9457 replaced it in July 2023. A body in that shape is sent with the media type application/problem+json, so a client can tell the shape from the label alone, before it reads a word.

Why it fits here: It dates this topic's shape: Problem Details has been a standard since 2016, labelled application/problem+json.

Sources: RFC 7807: Problem Details for HTTP APIs; RFC 9457: Problem Details for HTTP APIs

Topic: One shape for every error · standards, history

A thousand fields at most

A form body has a second limit, on how many fields it holds. body-parser's documentation says that its urlencoded reader allows at most 1000 parameters by default, set by the option parameterLimit, and that a request with more gets 413. Its error type is parameters.too.many, one more type for this topic's table of translations.

Why it fits here: It answers this topic's question: besides the size limit, a form body may hold at most 1000 fields by default.

Source: body-parser on GitHub

Topic: Errors from the parsers, and validation · numbers, tools

Three names for 413

The code 413 has had three names. RFC 2616 of 1999 called it Request Entity Too Large, RFC 7231 of 2014 Payload Too Large, and RFC 9110 of 2022 Content Too Large. The parser's error type entity.too.large keeps the oldest name, from the time when HTTP called a request's body its entity.

Why it fits here: It explains this topic's entity.too.large: the name comes from 1999, when 413 was Request Entity Too Large.

Sources: RFC 2616: Hypertext Transfer Protocol, HTTP/1.1; RFC 7231: HTTP/1.1 Semantics and Content; RFC 9110: HTTP Semantics

Topic: Errors from the parsers, and validation · history, words

One string is not an error

Anything passed to next is an error, with one exception. Express's guide says that if you pass anything to next() except the string 'route', Express treats the request as an error and skips every remaining handler that is not an error handler. So next("oops") starts the error chain, while next("route") moves on to the next route.

Why it fits here: It answers this topic's question: next() with any value but 'route' sends the request down the error chain.

Source: Express: Error handling

Topic: Several handlers, in order · tools, mistakes

Express 5 checks the status

Express 5 guards the status code. Its migration guide says that res.status accepts only integers from 100 to 999, following Node's own rule, and throws for anything else: res.status(99) throws. So a handler that copies err.status onto the answer checks it first, or a strange status becomes a second error inside the first.

Why it fits here: It warns this topic's handlers: an invalid err.status makes res.status throw, inside the error handler itself.

Source: Express: Migrating to Express 5

Topic: Several handlers, in order · tools, mistakes

Liveness and readiness

A server that hangs throws nothing, so platforms check on it from outside. Express's guide on health checks gives Kubernetes as an example, with two checks: liveness, which decides when to restart a container, and readiness, which decides when it may take traffic. Kubernetes' documentation adds that a liveness probe can catch a deadlock, where an application runs but makes no progress.

Why it fits here: It answers this topic's question: a liveness check asks a server from outside, and restarts it when it has hung.

Sources: Express: Health checks and graceful shutdown; Kubernetes documentation: Liveness, readiness and startup probes

Topic: The failures that are not errors · tools, internet

Retry-After, in seconds or as a date

Retry-After has two forms. RFC 9110 says its value can be an HTTP-date or a number of seconds to wait. With 503, it tells how long the service is expected to be unavailable; with a redirect, it gives the least time to wait before following it. So Retry-After: 120 and a date two minutes ahead say the same thing.

Why it fits here: It adds to this topic's Retry-After: it may hold seconds or a date, and it works with redirects too.

Source: RFC 9110: HTTP Semantics

Topic: The failures that are not errors · standards, tools

Lesson 7: WebSockets

Pushing before WebSockets

Before WebSockets, servers pushed news by bending HTTP. RFC 6202, of April 2011, describes the two common ways, long polling and streaming. In long polling, the server holds each request open and answers only when it has news, so a request is always waiting. Its abstract says that HTTP is often used, some would say abused, for such messages.

Why it fits here: It answers this topic's question: before WebSockets, long polling kept a request waiting until the server had news.

Source: RFC 6202: Known Issues and Best Practices for the Use of Long Polling and Streaming in Bidirectional HTTP

Topic: A line that stays open · history, internet

A standard in 2011, and over HTTP/2 in 2018

The WebSocket protocol became a standard in December 2011, as RFC 6455, and its handshake is an upgrade of an HTTP/1.1 request. HTTP/2 has no such upgrade, so in September 2018 RFC 8441 defined a way to run the WebSocket protocol over a single stream of an HTTP/2 connection instead.

Why it fits here: It dates this topic's handshake: RFC 6455 of 2011, joined in 2018 by a way to carry WebSockets over HTTP/2.

Sources: RFC 6455: The WebSocket Protocol; RFC 8441: Bootstrapping WebSockets with HTTP/2

Topic: A line that stays open · history, standards

Socket.IO is not a WebSocket

Socket.IO, a popular library above WebSockets, is not itself a WebSocket. Its documentation says so in capitals: Socket.IO is NOT a WebSocket implementation. It uses WebSocket for transport when it can, but adds metadata to each packet, so a WebSocket client cannot connect to a Socket.IO server, and a Socket.IO client cannot connect to a plain WebSocket server.

Why it fits here: It answers this topic's question: Socket.IO speaks its own format, so it cannot talk to a plain WebSocket server.

Source: Socket.IO documentation: Introduction

Topic: A server beside the routes · tools, mistakes

Node's own WebSocket is a client

Node has a WebSocket class of its own, but for one side only. Its manual says the global WebSocket was added in Node 21.0.0 and 20.10.0 and stopped being experimental in 22.4.0. The Node.js site explains that it lets Node act as a WebSocket client without libraries like ws, for client connections; a server still comes from a package, such as ws.

Why it fits here: It adds to this topic's server: Node's built-in WebSocket only connects, so serving still needs ws.

Sources: Node.js manual: Globals (WebSocket); Node.js: WebSocket client

Topic: A server beside the routes · tools, history

Every client frame is masked

A browser does not send its messages exactly as written. RFC 6455 says that a client must mask all frames it sends to the server, with a 32-bit masking key chosen at random for each frame. The reason was an experiment run while the protocol was being written: it showed attacks that poisoned caching proxies in the wild.

Why it fits here: It answers this topic's question: every frame from a client is masked with a random key, to protect proxies.

Source: RFC 6455: The WebSocket Protocol

Topic: Messages: text, JSON and bytes · privacy, standards

100 MiB per message

The ws package caps the size of one message. Its documentation gives the option maxPayload a default of 10,48,57,600 bytes, which is 100 MiB, and says that 0 removes the limit. A server that expects small JSON messages, such as gauge readings, can set a much smaller limit of its own.

Why it fits here: It adds to this topic's messages: ws refuses a message over 100 MiB by default, and maxPayload sets the limit.

Source: ws documentation

Topic: Messages: text, JSON and bytes · numbers, tools

Messages that wait in line

A slow listener can fill a server's memory. The ws documentation says that a socket's bufferedAmount is the number of bytes queued by send() but not yet sent to the network. A broadcast to a phone on a weak line keeps adding to it, so a server can check bufferedAmount and skip, or close, a socket that falls too far behind.

Why it fits here: It answers this topic's question: messages to a slow listener wait in memory, counted by bufferedAmount.

Sources: ws documentation; MDN: WebSocket: bufferedAmount property

Topic: Many clients: broadcast and rooms · tools, numbers

Compression, off by default

WebSocket messages can be compressed. RFC 7692, of December 2015, defines the permessage-deflate extension for it. The ws package leaves it off by default on the server and on by default on the client, because it adds a significant overhead in performance and memory; its README suggests turning it on only if it is really needed.

Why it fits here: It adds to this topic's many listeners: compression saves bytes but costs memory, so ws leaves it off on servers.

Sources: RFC 7692: Compression Extensions for WebSocket; ws on GitHub

Topic: Many clients: broadcast and rooms · tools, standards

1006 is never sent

Code 1006 never travels down the line. RFC 6455 says it is a reserved value that must not be set as a status code in a Close frame by either side. It exists for programs that need a code meaning the connection closed abnormally, without a Close frame sent or received: a line that broke, so nobody could say goodbye.

Why it fits here: It answers this topic's question: 1006 is never sent; a program reports it itself when a line breaks with no Close frame.

Source: RFC 6455: The WebSocket Protocol

Topic: The life of a line · standards, mistakes

Add jitter to the delay

A growing delay is not quite enough. Marc Brooker's post on the AWS Architecture Blog, of 4 March 2015, showed that exponential backoff alone still leaves clusters of calls, as clients retry at the same moments. Its answer: the solution is not to remove backoff, but to add jitter, a random part in each delay, so that the retries spread out.

Why it fits here: It sharpens this topic's reconnect: a random part in each delay spreads clients out, where doubling alone keeps them together.

Source: AWS Architecture Blog: Exponential Backoff and Jitter

Topic: The life of a line · tools, mistakes