Skip to content

Add req.originalRoute, the full matched route pattern (#2501) - #73

Merged
abedmurrar merged 3 commits into
masterfrom
feat/router-info
Nov 22, 2026
Merged

abedmurrar merged 3 commits into
masterfrom
feat/router-info

Conversation

@abedmurrar

Copy link
Copy Markdown
Owner

Summary

Adds req.originalRoute (expressjs#2501): the full path pattern of the route that matched, the pattern of every router and sub-app mount it is under followed by its own path. For app.use('/api', router) and router.get('/users/:id'), GET /api/users/7 gives '/api/users/:id'. It is built when read, from records the router already has in hand while routing.

Changes

  • src/router/index.ts: when trimPrefix enters a mount that is not a / mount, it stores { layer, path, noSlash, parent } in req[mountMatch] and puts the parent back when the request comes back to next(). Where next() sets req.route, it also sets req[routeMatch] to the same kind of record, with the current mount as its parent.
  • src/router/lib/layer.ts: rawPath (router 2.3.0's line from feat: add listRoutes method to list registered routes pillarjs/router#174: the path as registered, arrays flattened) and rawMatchers (one matcher per rawPath entry; the same array as matchers unless the path nests arrays). Matching still uses matchers.
  • src/router/lib/symbols.ts (new; 2.3.0 has a file of this name for its own matchedRoute symbol) and src/router/lib/original-route.ts (new), which walks the records and joins the patterns.
  • src/express.ts: the getter on the request prototype, not enumerable, so Object.keys(express.request) still matches Express 5.3.0 (test/exports.js).
  • Typings (readonly originalRoute?: string | undefined), type tests, docs/api/request.md, docs/fork/differences.md, History, VENDORED and the ROADMAP row.

Behaviour

Case req.originalRoute Why
Nested routers, any depth '/api/v1/users/:id' every mount pattern is joined, without trailing slashes, as req.baseUrl joins paths; a mount used without a path adds nothing
Route / under /api '/api/' the route's own pattern is kept as is (round-trips through app.get)
Path arrays the entry that matched, the first one in order, nested arrays included same shape as 2.3.0's match.pattern (pillarjs/router#207)
RegExp route or mount undefined a RegExp has no path form: String(regexp) joined with paths is neither a path nor a RegExp, and the matched text would put IDs back into metric names. req.route.path still has it
app.use middleware, before any route undefined not a route
Sub-apps joined like routers app.use(path, subApp) mounts through the same trimPrefix
router.route() / app.route(), router.param() callbacks of a route set same code path as router.get()
Error handlers the route that failed; undefined if the error came before any route kept as long as req.route
404 handlers undefined if no route matched; else the last route that passed the request on same lifetime as req.route, so the two never disagree
req.route replaced by user code undefined the record must belong to req.route
After the response (res.on('finish')) still set the logging and metrics use case

Name. Upstream discussion never settled a name: pillarjs/router#34 and pillarjs/router#86 used req.matchedRoutes (an array of every matched path, built on every request, never finished), with matchedPaths / matchedPathnames floated in review. Kept originalRoute from the roadmap: it is to req.route what req.originalUrl is to req.url.

Rejected alternatives. Re-matching the app's router tree at read time (ambiguous with routers mounted twice or falling through to siblings, and breaks on rewritten req.url). Building the string or an array per request (the cost the issue's earlier PRs carried). A WeakMap per request (costs more than a property store). Porting 2.3.0's matchers = rawPath.map(matcher) (would make a nested array holding a RegExp stop throwing at registration, which changes existing behaviour; the re-sync brings it).

Proof

  • npm run lint, npm run typecheck, npm run test:types: clean.
  • npm run test-ci: 146 files, 8694 passed, 5 skipped; 100% statements, branches, functions and lines; coverage-files check passes.
  • 39 new tests in test/req.originalRoute.js. Planted breaks: removing the route record fails 30 of them, removing the mount record fails 21, removing the restore of the parent mount fails 3.
  • Middleware suites (node scripts/ecosystem-suites.js): every test that passes on Express 5.3.0 passes here (cors 49, express-session 160, multer 173, express-rate-limit 252, http-proxy-middleware 325, express-basic-auth 25, express-openapi-validator 468, express-fileupload 203, express-mongo-sanitize 20, hpp 17).
  • No differential allowed entry.

Benchmark

Local instruction count, node benchmarks/count/run.ts --counter valgrind --runs 1 --jobs 2 --against origin/master --report-only:

scenario baseline head change
hello 78.02k 78.09k +0.08%
json 86.61k 86.74k +0.14%
params 81.33k 81.42k +0.11%
mw10 94.21k 94.26k +0.05%
routes100 122.06k 122.27k +0.17%
post-json 124.64k 124.82k +0.14%
not-found 100.78k 98.99k -1.78%
query 103.22k 103.21k -0.00%

All under the +0.3% goal. The route scenarios pay about 70 to 210 instructions per request for one small record and one symbol-keyed store per matched route; middleware pays one layer.slash check, and next() one closure check. not-found (no route matched) has nothing new to do; its -1.78% is not explained by this change and is worth re-measuring.

Risks / follow-ups

  • util.inspect(req) now lists the two symbol-keyed records (2.3.0's req[matchedRoute] does the same), and console.dir(req.route) shows rawPath and rawMatchers on each layer (the req.route docs example is updated).
  • The getter lives in src/express.ts because src/request.ts is being changed in a parallel PR; it can move there later.
  • History.md and differences.md get a new "Additions" heading, as Add the "view engines" setting: try several engines for a view name without a known extension #72 does; whichever merges second should fold the two into one.
  • Router 2.3.0 re-sync: layer.match() returns match.pattern, which can go into the records and replace the re-matching in original-route.ts; rawMatchers then goes away (see VENDORED.md).

req.originalRoute is the pattern of every mount the route is under, then
the route's own path: '/api/users/:id' for router.get('/users/:id') under
app.use('/api', router). The router records each mount it enters and each
route it matches on the request; the string is built only when read.

Mount patterns are joined as req.baseUrl joins paths, a path array gives
the entry that matched, a RegExp route or mount gives undefined, and the
value is kept as long as req.route is. The getter is not enumerable, so
the request prototype keeps the keys of Express 5.3.0.

Layer gains rawPath (router 2.3.0's line from pillarjs/router#174) and
rawMatchers; matching itself is unchanged.
@coveralls

Copy link
Copy Markdown

Coverage Report for CI Build 45032051789

Coverage remained the same at 100.0%

Details

  • Coverage remained the same as the base build.
  • Patch coverage: 185 of 185 lines across 5 files are fully covered (100%).
  • No coverage regressions found.

Uncovered Changes

No uncovered changes found.

Coverage Regressions

No coverage regressions found.


Coverage Stats

Coverage Status
Relevant Lines: 9864
Covered Lines: 9864
Line Coverage: 100.0%
Coverage Strength: 32613.72 hits per line

💛 - Coveralls

@abedmurrar
abedmurrar merged commit 575ca78 into master Nov 22, 2026
12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants