Dynamic Route Matching
Very often we need to map routes with the given pattern to the same component. For example, we may have a UserProfile component which should be rendered for all users but with different user IDs. In @esmx/router, we can use a dynamic segment in the path to achieve that.
Route Params
Dynamic segments are denoted by a colon :. When a route is matched, the value of the dynamic segments will be exposed as route.params:
Now URLs like /users/42 and /users/alice will both map to the same route:
All param values are strings. Even if the URL contains /users/42, route.params.id will be the string '42', not the number 42.
Multiple Params
You can have multiple dynamic segments in the same route, and they will map to corresponding fields on route.params:
Optional Params
You can make a parameter optional by adding a ? after it. Optional parameters will match routes both with and without the segment:
When an optional parameter is not present in the URL, its value will be an empty string ''.
Catch-All / 404 Routes
A wildcard pattern can catch all paths — useful for 404 pages or fallback routes. Use the (.*) pattern (or (.*)* for capturing the value as an array):
Make sure to place your catch-all route last in the routes array. Since routes are evaluated in order, a catch-all at the top would match every URL and prevent specific routes from ever being reached.
Accessing Params
route.params
An object containing key/value pairs of dynamic segments. Each value is a string. For repeating parameters (like (.*)*), only the first match is provided:
route.paramsArray
An object containing key/value pairs where each value is a string array. This is useful for repeating parameters and ensures you always get all matched values:
Query Params
Query parameters are the key/value pairs after the ? in a URL. They don't need to be defined in the route pattern — they're always available:
route.queryArray
For query parameters that appear multiple times, use queryArray to get all values:
route.query:Record<string, string | undefined>— First value for each query keyroute.queryArray:Record<string, string[] | undefined>— All values for each query key
Hash
The hash fragment (everything after # in the URL) is available via route.hash:
The hash always includes the # prefix. If there's no hash in the URL, route.hash is an empty string.
Pattern Matching with path-to-regexp
Under the hood, @esmx/router uses the path-to-regexp library for pattern matching. This gives you access to advanced matching features:
Custom Regex Constraints
You can restrict what a parameter matches using inline regex:
URL Encoding
Route paths should be URL-encoded. The router handles encoding and decoding automatically — when you define routes and access parameters, you work with decoded values:
When navigating programmatically, you can pass either encoded or decoded paths: