Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions History.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ Unreleased (fork)

## ✨ Additions

* `diagnostics_channel` events (PR #6959, #7041, issue #6353), for APMs and tracers. Every middleware, route handler, error handler and `app.param()` callback the router runs is traced through the `express.router.request` `TracingChannel`, ported from router 2.3.0 (pillarjs/router#196, #207 and #223 by Abdelrahman Awad (logaretm), and #215 by Sebastian Beltran (bjohansebas)): `start` and `end` around the call, `asyncStart` and `asyncEnd` when a returned promise settles, and `error` once per error, where it starts (`next(err)`, a throw or a rejection). The context has `req`, `res`, `handler`, `layer`, `route` (the pattern that matched, such as `'/users/:id'` or a mount path), and `param`, `errorHandler`, `incomingError`, `error` and `result` where they apply, the same channel and payload as router 2.3.0, so subscribers written for it work unchanged; stores bound on `start` follow the request into async handlers. `express()` publishes `{ app }` on `express.initialization` (from PR #7041 by DemianParkhomenko, Fastify's `fastify.initialization`). With no subscribers nothing is published, no context is built and no error is recorded: each router and each route checks `hasSubscribers` once per request, where router 2.3.0 checks before every handler and stores the matched pattern on every request (instruction count -0.02% to +0.18% per request; router 2.3.0's way measured up to +1.05%). Subscriber errors don't reach the request (Node rethrows them on the next tick). PR #6959's `express.request.*`, `express.middleware.*` and `express.route.match` channels are not taken: they wrapped every handler at registration (changing `layer.handle` and adding work to every call), and Node's `http.server.request.start` and `http.server.response.finish` already mark a request's start and end. Documented in docs/api/diagnostics.md, typed as `RouterTraceContext` and `InitializationMessage`.
* Warn, on the `express:router` debug namespace, about routes that can't work as written, when they are registered: a path no request can match (#2511), because its literal text has a space, a control or non-ASCII character, a `?` or a `#` (none of which is ever in a request's still-encoded path), or doesn't start with `/`, with the character's encoded form; and the same method and path registered twice on the same router, naming both by stack index and handler name. Only what the path string proves is flagged. Nothing is printed without `DEBUG=express:router` (or `express:*`), and the checks only run while it is enabled, so they cost nothing per request.
* Add `req.originalRoute` (#2501): the full path pattern of the route that matched, the path of every router and sub-app it is mounted under followed by its own, so `router.get('/users/:id')` under `app.use('/api', router)` gives `'/api/users/:id'` for `GET /api/users/7`. Mount paths are joined as `req.baseUrl` joins them, a path array gives the entry that matched, and a RegExp route or mount gives `undefined`, since it has no path form. It is set and kept exactly as long as `req.route` is, so error handlers see the route that failed, and a 404 handler sees `undefined` unless a route matched and passed the request on. The router records the mounts and the route as it goes, and the string is built only when read; the request prototype's enumerable keys are unchanged. Upstream's proposals (pillarjs/router#34 and #86, `req.matchedRoutes`) built an array of every matched path on every request and were never finished.
* The `ERR_HTTP_HEADERS_SENT` error thrown when a response method is called after the headers were sent names the method (expressjs/express#7560): `Cannot set headers after they are sent to the client: res.json() was called after the response headers were sent`, where Express 5.3.0 gave Node's message alone. It covers `res.send`, `res.json`, `res.jsonp`, `res.sendStatus`, `res.redirect`, `res.render` (passed to `next(err)` without a callback), `res.set`, `res.append`, `res.cookie`, `res.clearCookie`, `res.location`, `res.type`, `res.attachment`, `res.links`, `res.vary` and `res.format`, and names the method the app called (`res.json()`, not the `res.set()` inside it). Only the message changes: it is the same error object, with the same class, `code` and stack frames, thrown or forwarded from the same place, and Node's text is still its start. Each method names it in a `catch` block, so nothing runs unless the error is thrown.
Expand Down
2 changes: 1 addition & 1 deletion ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@ These are opt-in, and nothing existing changes.
| Status | Item | Upstream | Line | Size | Proof | PR |
|---|---|---|---|---|---|---|
| [x] | `req.signal`, which aborts when the client disconnects | | master | Small | Express's own lazy, non-enumerable accessor on the request prototype, the same on Node 22, 24 and 26: Node 22 has no `IncomingMessage#signal`, and 24.16 to 24.19 and 26.1 to 26.6 abort theirs after every response (nodejs/node#64390, fixed in 24.20 and 26.7). The reason is the default `AbortError` `DOMException`, as for Node and Fastify. 18 new tests (abort on disconnect, `res.destroy()`, a pipelined request, a POST after its body; no abort after a finish, keep-alive or `Connection: close`; read late; sub-apps; no leak over 200 keep-alive requests), passing on Node 22 and 24. 10 planted breaks each fail 1 to 6 of them. Assigning `req.signal` still sets an own property, as on Node 22 with Express 5.3.0. Instruction count within noise | [#75](https://github.com/abedmurrar/express/pull/75) |
| [ ] | `diagnostics_channel` events | PR #6959 | master | Medium | new tests | |
| [x] | `diagnostics_channel` events | PR #6959 | master | Medium | router 2.3.0's `express.router.request` TracingChannel (pillarjs/router#196, #207, #215, #223) ported into the vendored router with the same name, events and context, so subscribers written for it work unchanged; `express()` publishes `{ app }` on `express.initialization` (PR #7041). PR #6959's own channels not taken (it wraps every handler at registration; Node's `http.server.request.start`/`response.finish` already mark the request). Without subscribers: no publish, no context, no error recording (a spy on all six channels sees zero calls); one subscriber check per router and per route, which picks each layer's untraced method (byte for byte router 2.2.0's) or traced one. Same responses and call order with subscribers, and with subscribers that throw (child process). 174 new tests (router 2.3.0's 151, 23 through Express apps); 26 planted breaks each fail 1 to 71. Instruction count -0.02% to +0.18% (2.3.0's per-handler check measured up to +1.05%) | [#84](https://github.com/abedmurrar/express/pull/84) |
| [ ] | `app.listRoutes()` | PR #7531, router#174 | master | Medium | new tests; router part arrives with the 2.3.0 re-sync | |
| [x] | Explicit error-handler API (`app.error`, `router.error`); counting arguments still works | #2896, #3367, router#59 | master | Medium | `app.error([path], ...fns)` and `router.error([path], ...fns)` take `use()`'s arguments and mount the same way, but the layer is marked `errorOnly` (`false` on the prototype), so it runs only for an error, whatever its `length`; length 4 through `use()` or inline in a route is unchanged. A router or an app given to `error()` throws `EXPRESS_ERR_ERROR_HANDLER_IS_ROUTER`. `app.error` is mixed into each app, so `express.application` keeps 5.3.0's own properties; typed on the global `Express.Application`, and `router.error` on what `express.Router()` returns (`RouterWithErrorHandlers`), so `@types` apps and routers stay assignable both ways. No `route.error()`: a required member on `IRoute` breaks that interop. 46 new tests (wrapped, bound, default and rest parameters, async; paths; sub-apps; nested routers; `next(err)` and `next()`; order with `use()`); 9 planted breaks each fail 1 to 41. Instruction count (valgrind, local): -0.02% to +0.20% | [#85](https://github.com/abedmurrar/express/pull/85) |
| [x] | Clearer error when a response is sent twice | #7560 | master | Small | Node's `ERR_HTTP_HEADERS_SENT` message gets `: res.json() was called after the response headers were sent`, naming the Express method the app called (the outermost of `res.send`, `json`, `jsonp`, `sendStatus`, `redirect`, `render`, `set`, `append`, `cookie`, `clearCookie`, `location`, `type`, `attachment`, `links`, `vary` and `format`). Same object, class, `code` and stack frames, thrown or forwarded from the same place, and Node's text is still the start. It is named in `catch` blocks only, so instruction count is within ±0.09%. 30 new tests compare each case with Express 5.3.0; 8 planted breaks each fail 1 to 27 of them. `res.sendFile`/`res.download` keep `send`'s own 500 message | [#76](https://github.com/abedmurrar/express/pull/76) |
Expand Down
9 changes: 8 additions & 1 deletion VENDORED.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ All seven copies are the same versions Express 5.3.0 installs here, and match th

`serve-static`'s source is our fork, https://github.com/abedmurrar/serve-static, created from expressjs/serve-static with only its default branch. Nothing is pushed to it yet: its `master` is upstream's, and the vendored code is upstream's tag `v2.2.1` (commit `76312e12c2754c226a685201ff43d785455d0590`, which the fork's `master` contains; the fork has no tags). Upstream's `master` has one later change to `index.js`, a comment typo fix (`fall-though` to `fall-through`, expressjs/serve-static#246), which is not released and not in our copy.

`router` 2.3.0 (published 2026-11-17) is not vendored yet. This machine's npm config only accepts releases at least 7 days old, so it waits until 2026-11-24 and goes in as a re-sync. It fixes a rewritten `req.url` losing a slash in a mounted router (upstream issue #4059, pillarjs/router#206), but none of the three routing fixes below (`//` mounts, router cycles, `#` fragments), and adds `router.listRoutes()` (pillarjs/router#174) and request tracing channels (pillarjs/router#196).
`router` 2.3.0 (published 2026-11-17) is not vendored yet. This machine's npm config only accepts releases at least 7 days old, so it waits until 2026-11-24 and goes in as a re-sync. It fixes a rewritten `req.url` losing a slash in a mounted router (upstream issue #4059, pillarjs/router#206), but none of the three routing fixes below (`//` mounts, router cycles, `#` fragments), and adds `router.listRoutes()` (pillarjs/router#174) and request tracing channels (pillarjs/router#196), whose tracing is already ported (see the tracing edit below).

`express.static` is our `lib/serve-static`, which loads our `lib/send`, so `express.static`, `res.sendFile` and `res.download` all use the same `send`. The `serve-static` package (and the npm `send` it brings) is no longer a dependency; npm still installs both for the development-only `express-baseline` (Express 5.3.0, the differential harness's baseline).

Expand Down Expand Up @@ -54,11 +54,18 @@ All seven copies are the same versions Express 5.3.0 installs here, and match th
- `router.error()` (expressjs/express#2896): `use()` for error handlers, which run only for an error whatever their `length`. Not in router 2.2.0 or 2.3.0 (pillarjs/router#59, open since 2017, proposed it along with deprecating the length check, which we keep). `src/router/lib/layer.ts`: the `Layer` interface has `errorOnly: boolean`, set to `false` on the prototype after `const proto = Layer.prototype as Layer` (so layers that don't use it get no own property); `handleError` now passes the error on when `fn.length !== 4 && !this.errorOnly` (was `fn.length !== 4`), and `handleRequest` passes the request on when `fn.length > 3 || this.errorOnly` (was `fn.length > 3`). `src/router/index.ts`: the `Router` interface has `error()`, and `proto.error` (after `proto.use`) calls `this.use(...)`, then sets `errorOnly` on the layers it added, or removes them all and throws `EXPRESS_ERR_ERROR_HANDLER_IS_ROUTER` when one of them is a router or an app (a function with a `handle` method). When re-syncing, keep the two conditions and `proto.error`; `route.ts` is untouched.
- Error codes (expressjs/express#6951): every error the router creates gets a stable `code` from Express's `withCode` helper (`src/error-code.ts`, required as `../error-code` from `index.ts` and `../../error-code` from `lib/layer.ts` and `lib/route.ts`), which defines `code` as a writable, configurable, non-enumerable own property on the error the call site just created, so messages, classes and stack frames stay upstream's. Not in router 2.2.0 or 2.3.0. `index.ts`: the four `param()` checks (`EXPRESS_ERR_PARAM_NAME_REQUIRED`, `EXPRESS_ERR_PARAM_NAME_NOT_STRING`, `EXPRESS_ERR_PARAM_CALLBACK_REQUIRED`, `EXPRESS_ERR_PARAM_CALLBACK_NOT_FUNCTION`), `handle()` without a callback (`EXPRESS_ERR_ROUTER_CALLBACK_REQUIRED`), `use()` without a handler or with one that isn't a function (`EXPRESS_ERR_HANDLER_REQUIRED`, `EXPRESS_ERR_HANDLER_NOT_FUNCTION`), our mount-on-itself check (`EXPRESS_ERR_ROUTER_MOUNTS_ITSELF`), our `error()` given a router or an app (`EXPRESS_ERR_ERROR_HANDLER_IS_ROUTER`) and the `Rejected promise` error of a param callback (`EXPRESS_ERR_REJECTED_PROMISE`). `lib/route.ts`: the same two handler checks in `all()` and in each method. `lib/layer.ts`: the two `Rejected promise` errors (`handleRequest`, `handleError`), and `decodeParam`'s 400 `URIError` (`EXPRESS_ERR_PARAM_DECODE_FAILED`, set after its `status`). When re-syncing, wrap any new `new Error`/`new TypeError` the same way and add its code to docs/api/errors.md (the `fork-error-codes` tests check the list).

- Tracing (`diagnostics_channel`), ported from router 2.3.0 before the re-sync: the `express.router.request` TracingChannel of pillarjs/router#196, with the matched pattern of #207, the parameter callbacks and error attribution of #215 and the terminal-event rules of #223. Same channel name, events and context, so the re-sync keeps this code. `src/router/lib/tracing.ts` (new) is 2.3.0's `lib/tracing.js` typed, plus its `lib/param.js` (`callParam`) as a private helper that only the traced path uses; it exports the `TraceContext` type, and requires `node:diagnostics_channel` without 2.3.0's `dc.tracingChannel &&` guard (Node 22 has it). `src/router/lib/symbols.ts`: 2.3.0's `matchedRoute` symbol. `src/router/lib/layer.ts`: `handleError` and `handleRequest` are unchanged; two new methods after them, `traceError` and `traceRequest`, do the same with 2.3.0's traced path (the not-a-handler checks, then 2.3.0's `invokeWithTrace` call with its context), and `invokeWithTrace` (2.3.0's) follows them. Their callbacks are named `invokeErrorHandler` and `invokeHandler` (anonymous upstream; lcov rejects their duplicate inferred names). `src/router/index.ts`: `handle()` checks `requestChannel.hasSubscribers` once (`var traced`, after the `restore` line: a `var`, so `next()` and `trimPrefix` read it without a temporal-dead-zone check), and when traced wraps `done` in a second `restore` for `req[matchedRoute]`; when traced, `trimPrefix` sets `req[matchedRoute]` with the new `setMatchedRoute` helper (placed before `mergeParams`) and calls `traceError`/`traceRequest` instead of `handleError`/`handleRequest`; a route's own layer always gets `handleRequest` (`route.dispatch` traces its handlers); when traced, `next()` calls `setMatchedRoute` for a matched route, in the block that sets `req.route` (not in the `processParams` callback, which would make `noSlash` a context variable that the matching loop reads for every layer); `next()` records `err`, and the loop records a matching error, with `recordError`; and `paramCallback` calls `setMatchedRoute` and `traceParam` when there are subscribers. `src/router/lib/route.ts`: `dispatch()` checks once (`var traced`, requiring `requestChannel` from `./tracing`), and its `next()` calls `traceError`/`traceRequest` when traced. How this copy differs from 2.3.0:
- The subscriber check is made once per router and once per route as they start on a request, and picks each layer's traced or untraced method, where 2.3.0 checks inside `handleError` and `handleRequest` before every handler (with the traced call's closure in them) and sets `req[matchedRoute]` in `next()` for every matched layer, and restores it, on every request. Here it is set only while traced, right before the parameter callbacks or the handler run. 2.3.0's way counted 0.5% to 1% more instructions per request with no subscribers (hello +0.48%, mw10 +1.05%), over the 0.3% budget; with the check moved out but the traced path still inside the two methods, mw10 was still +0.43%. A subscriber that attaches during a request is seen from the next router or route the request enters. Keep this when re-syncing.
- The untraced paths are 2.2.0's, unchanged: 2.3.0 rewrote them around a `handlePromise` helper and `callParam`, passing a no-op instead of `null` to a returned promise's `then`, so a broken thenable that calls `then`'s first callback without checking it no longer gets a `TypeError` to `next()`. Here that change only applies while traced (`invokeWithTrace` and `callParam` pass functions, as 2.3.0 does); the re-sync brings it to the untraced path.
- Errors are recorded only while the channel has subscribers (`requestChannel.hasSubscribers` before both `recordError` calls in `index.ts`), so an untraced request gets no `Symbol.for('router.tracing.publishedErrors')` set. 2.3.0 records every error, so a subscriber that attaches while an error is already on its way can't blame a forwarder; here that's covered when the error passes a router or reaches an error handler after the subscriber attached (2.3.0's tests for it pass), and missed only if it did both before. Keep the guards when re-syncing.
- The pattern comes from `layer.rawPath` (`matchedPattern` from `./original-route` for a path array, run only while traced), since `match()` still returns `true` here: 2.3.0's `match()` returns it as `match.pattern` (pillarjs/router#216). After the re-sync, `req[matchedRoute] = match.pattern` replaces it.

### router tests

- `require('..')` changed to `require('../../lib/router')`.
- Removed the first-line `const { it, describe } = require('mocha')` from the 7 router test files, so they use the test runner's globals (Vitest).
- Added `require('node:buffer')` in `support/utils.js`, `router.js` and `route.js`, for the same lint rule.
- `tracing.js` (from router 2.3.0, with the tracing edit above), with the same two changes, and the copy-loading helper's `require.resolve('..')` changed to `require.resolve('../../lib/router')`. These tests differ: the one that calls an error handler's layer directly calls `traceError` instead of `handleError` (see the tracing edit above); the URL-decoding tests answer with `err.status`, since 2.3.0's `statusCode` on that error (pillarjs/router#171) isn't here yet; and the test that a broken thenable gets no `TypeError` without subscribers now checks that it still does (router 2.2.0's untraced path, see above), while the traced case keeps 2.3.0's test.

### send

Expand Down
Loading