skip to content

In Express 5, how do you write a named wildcard, an optional segment and a digits-only parameter in a route path without inline regex?

level: middleimportance: should knowfreq 35%

answer

  1. path-to-regexp v8
  2. a star needs a name
  3. braces mark optional parts
  4. RegExp object, not inline

basics

~20 s

Express 5 parses string paths with path-to-regexp v8: a wildcard needs a name such as /*splat and captures an array, braces make a part optional as in /:file{.:ext}, and a digits-only rule needs a RegExp route.

solid answer

~40 s

Express 5 hands string paths to path-to-regexp v8. A named parameter `:id` captures one segment, or part of one, as in `/flights/:from-:to`. A wildcard must be named, `/files/*filepath`, matches one or more segments and lands in `req.params` as an **array**; wrap it as `/{*splat}` to match the root too. Braces mark an optional part, `/export/:name{.:ext}` or `/order{/:id}`, and an absent optional parameter is left out of `req.params`. String paths take no regex at all, and `()[]?+!` are reserved, so `:id(\d+)` throws; escape a literal with a backslash. For a digits-only id, register a `RegExp` route such as `/^\/sku\/(\d+)$/`, list alternatives in an array, or validate the value in a handler.

code

javascript · 17 lines
javascript
const express = require('express');
const app = express();

// GET /files/img/logo.png -> { filepath: [ 'img', 'logo.png' ] }
app.get('/files/*filepath', (req, res) => res.json(req.params));

// GET /export/report.csv -> { name: 'report', ext: 'csv' }
// GET /export/report     -> { name: 'report' }
app.get('/export/:name{.:ext}', (req, res) => res.json(req.params));

// GET /sku/42 -> { '0': '42' }; GET /sku/ab does not match
app.get(/^\/sku\/(\d+)$/, (req, res) => res.json(req.params));

// Alternatives as an array instead of '/(discussion|page)/:slug'
app.get(['/discussion/:slug', '/page/:slug'], (req, res) => res.json(req.params));

app.listen(3000);

go deeper

for a junior

Recall the new shapes: named wildcards like *splat, braces for optional parts, and that string paths no longer take regex characters.

for a middle

Explain how each form fills req.params, why the slash position inside braces matters, and when to switch to a RegExp route or an array of paths.

for a senior

Show you can translate a legacy route table safely, including handlers that read wildcard values or test for absent parameters.

for a principal

Decide whether format rules belong in route patterns or in validation code, given what each choice does to error responses and route fall-through.

## Where the syntax comes from Express 5 does not parse route strings itself. Routing lives in the separate `router` package, which turns every **string path** passed to `app.METHOD`, `app.all`, `app.use` and their `express.Router` counterparts into a matcher with **path-to-regexp v8**. That version deliberately dropped the regex-flavoured syntax that Express 4 accepted, so a route string is now a small language of its own with four building blocks. ## The four building blocks | Form | Example | Matches | `req.params` | | --- | --- | --- | --- | | Named parameter | `/users/:userId` | one segment | `{ userId: '34' }` | | Wildcard | `/files/*filepath` | one or more segments | `{ filepath: ['img', 'logo.png'] }` | | Optional group | `/export/:name{.:ext}` | with or without `.ext` | `{ name: 'report' }` when absent | | Quoted name | `/:"user-name"/x` | one segment | `{ 'user-name': 'bob' }` | Some rules that follow from the table: - A **named parameter** matches up to the end of the segment or up to the next literal, so `/flights/:from-:to` splits `LAX-SFO` and `/plantae/:genus.:species` splits on the dot. Names must be valid JavaScript identifiers unless quoted. - A **wildcard** must have a name; a bare `*` is an error. It needs at least one segment, so `/files/*filepath` does not match `/files`. Its value is an **array of segments**: join it with `'/'` when you need the string. - **Braces** make everything inside them optional, which means the position of the slash matters: `/order{/:id}` matches `/order` and `/order/42`, while `/user/{:id}` requires the trailing slash and does not match `/user`. `/{*splat}` combines the two ideas into a catch-all that also matches `/`. - An optional parameter that is absent is **omitted** from `req.params`; there is no key with the value `undefined`. ## What string paths no longer accept String paths carry **no regular-expression features**. The characters `(`, `)`, `[`, `]`, `?`, `+` and `!` are reserved, and braces are reserved for optional groups, so writing any of them makes registration throw a `TypeError` that names the path and the index of the bad character. To match one of them literally, escape it: the JavaScript string `'/q/\\(x\\)'` matches the request path `/q/(x)`. Three common Express 4 habits therefore need a new spelling: 1. **A constrained parameter** such as `'/items/:id(\\d+)'`: register a `RegExp` route instead, or accept any segment and validate it in the handler. 2. **Alternatives** such as `/(discussion|page)/:slug`: pass an array of paths, `['/discussion/:slug', '/page/:slug']`. 3. **An optional suffix** such as `/:file.:ext?`: move the optional part into braces, `/:file{.:ext}`. ## Regular-expression routes still work What went away is regex *inside a string*. A real `RegExp` object is still a valid route path and is matched as written: ```js app.get(/^\/sku\/(\d+)$/, (req, res) => { res.json({ sku: req.params[0] }); // GET /sku/42 -> { sku: '42' } }); app.get(/^\/n\/(?<num>\d+)$/, (req, res) => { res.json(req.params); // GET /n/7 -> { num: '7' } }); ``` Unnamed groups land in `req.params` under numeric keys (`0`, `1`, ...), and named groups under their names. A request such as `/sku/ab` simply fails this route and continues down the stack. Note one more difference: for string paths `req.params` is an object with a **null prototype**, so call `Object.hasOwn(req.params, 'id')` rather than `req.params.hasOwnProperty('id')`; for a `RegExp` path it is an ordinary object. ## Decoding and matching details A few behaviours apply to every string path, whatever form it uses: - Captured values are **decoded** with `decodeURIComponent`, so `/users/J%C3%BCrgen` gives `req.params.userId` the decoded string. A malformed escape such as `%E0%A4%A` makes the router raise an error with status 400 and the message `Failed to decode param`. - Matching is **case-insensitive** and a **trailing slash is optional** by default; the `caseSensitive` and `strict` options of `express.Router()` (or the app settings `case sensitive routing` and `strict routing`) turn either off. - The **query string** never takes part in the match: `/export/report.csv?inline=1` matches `/export/:name{.:ext}` like the bare path. - Express reads the path **once, at registration**, so a syntax mistake surfaces as soon as the module that registers the route is loaded, not on the first request. ## Choosing the right form - One variable segment: `:name`. - Everything below a prefix, as segments: `*name`, or `{/*name}` when the prefix alone must match too. - An optional piece: braces around exactly the characters that may be missing. - A format rule on a segment: a `RegExp` route for routing decisions, or validation code when a bad value should produce a 400 rather than fall through to another route. - Several literal spellings of one route: an array of paths.

  • In Express 5, how do you match a literal parenthesis or plus sign in a route path?
    Escape it with a backslash in the path string. Those characters are reserved by path-to-regexp v8, so an unescaped `(` or `+` makes registration throw a `TypeError`. In JavaScript source the backslash itself must be doubled, as in `'/q/\\(x\\)'`, which matches the request path `/q/(x)`.
  • Why might you validate a numeric id in the handler instead of using a RegExp route in Express 5?
    A `RegExp` route that does not match lets the request fall through to later routes and usually ends in a 404. When a malformed id should get a clear 400 with an explanation, accept any segment with `:id` and check it in a handler or an `app.param` callback, where you control the response.

  • A bare * still works as a catch-all route in Express 5.
  • Wildcard captures in Express 5 are strings like 'a/b', not arrays.
  • You can still restrict a parameter inline with :id(\d+) in a string path.
  • Express 5 dropped support for RegExp route paths entirely.
  • An absent optional parameter shows up in req.params with the value undefined.

Assumes Express 5, which routes through path-to-regexp v8; Express 4 accepted *, ?, + and inline regex in string paths.