---
title: "RegExp Router"
description: "The `RegExpRouter` is a high-performance routing engine designed for speed by converting standard URL routing patterns into a single, optimized regular expression. Unlike naive routers that perform..."
last_updated: "2026-07-02T09:13:46.836208+00:00"
canonical_url: "https://www.doc0.app/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing-algorithms/regexp-router"
---

<details>
<summary>Relevant source files</summary>

The following files were used as context for generating this wiki page:

- [src/types.ts](https://github.com/blade47/hono/blob/main/src/types.ts)
- [package.json](https://github.com/blade47/hono/blob/main/src/package.json)
- [src/client/client.ts](https://github.com/blade47/hono/blob/main/src/client/client.ts)
- [src/router/reg-exp-router/router.ts](https://github.com/blade47/hono/blob/main/src/router/reg-exp-router/router.ts)
- [src/preset/quick.ts](https://github.com/blade47/hono/blob/main/src/preset/quick.ts)
- [src/router/reg-exp-router/prepared-router.ts](https://github.com/blade47/hono/blob/main/src/router/reg-exp-router/prepared-router.ts)
- [src/hono.ts](https://github.com/blade47/hono/blob/main/src/hono.ts)
- [src/utils/url.ts](https://github.com/blade47/hono/blob/main/src/utils/url.ts)
- [src/router/linear-router/router.ts](https://github.com/blade47/hono/blob/main/src/router/linear-router/router.ts)
- [src/helper/ssg/ssg.ts](https://github.com/blade47/hono/blob/main/src/helper/ssg/ssg.ts)
</details>

The `RegExpRouter` is a high-performance routing engine designed for speed by converting standard URL routing patterns into a single, optimized regular expression. Unlike naive routers that perform linear scans or depth-first tree traversals for every incoming request, `RegExpRouter` compiles the entire routing table into a regex-based matcher. This design minimizes the per-request overhead, making it particularly effective in environments where routing performance is a critical path.

The architecture relies on a `Trie` data structure to preprocess route definitions. During the registration phase, the router tracks path structures and converts variables (like `:id`) and wildcards (`*`) into corresponding capturing groups. This structure is then serialized into a regular expression. When a request arrives, the router uses this single regex to identify the matching handler index in a single pass, significantly reducing the algorithmic complexity of route resolution.

`RegExpRouter` is one of the foundational routers used within Hono. It is typically employed by the `SmartRouter`, which combines different routing strategies to provide the best balance of flexibility and performance. By implementing the `Router` interface, it remains drop-in compatible with other routing implementations, allowing developers to switch underlying engines without altering their business logic.

## The Trie Preprocessing Mechanism

Before a regex can be generated, the router must organize the input paths into a `Trie` structure. This ensures that hierarchical path segments are handled correctly and that potential routing ambiguities are resolved. The `Trie` insertion logic acts as the primary registry for path segments.

When `add(method, path, handler)` is called:
1. The path is tokenized into segments.
2. The `Trie` structure is updated by calling `trie.insert(path, j, pathErrorCheckOnly)`.
3. If a segment contains a parameter (e.g., `:id`), it is handled by the trie nodes to facilitate correct index generation for the final regex output.

Sources: [src/router/reg-exp-router/router.ts:L132-L204](https://github.com/blade47/hono/blob/main/src/router/reg-exp-router/router.ts#L132-L187), [src/router/reg-exp-router/trie.ts](https://github.com/blade47/hono/blob/main/src/router/reg-exp-router/trie.ts)

## Regex Compilation Logic

Once all routes are registered, the `RegExpRouter` invokes `buildMatcherFromPreprocessedRoutes`. This function performs the transformation from a structured `Trie` to an executable `RegExp` instance.

The compilation process:
1. Traverses the built trie via `trie.buildRegExp()` to generate a path-matching regex.
2. Captures parameter groups so they can be extracted during the `match` operation.
3. Finalizes the regex, which acts as the "Compiled Routing Table" used to dispatch incoming requests.

```mermaid
flowchart TD
    A[Start: Build Matcher] --> B[Traverse Trie]
    B --> C[trie.buildRegExp]
    C --> D[Generate Regex Instance]
    D --> E[Finalize Handler Mapping]
    E --> F[Return Matcher]
```
Sources: [src/router/reg-exp-router/router.ts:L34-L103](https://github.com/blade47/hono/blob/main/src/router/reg-exp-router/router.ts#L34-L103)

## Static Path Handling

The `RegExpRouter` separates path matching into logic for static paths and patterns. During the build process, routes are flagged via a boolean as `!/\*|\/:/.test(route[0])`. Routes without parameters are stored as static entries. During the `match` operation, these are evaluated to ensure optimal performance for standard, non-parameterized routes.

> [!TIP]
> Placing frequently accessed static routes, such as `/health`, before dynamic routes can improve performance in high-throughput applications, as the router optimizes for these constant paths during the trie construction.

Sources: [src/router/reg-exp-router/router.ts:L43-L56](https://github.com/blade47/hono/blob/main/src/router/reg-exp-router/router.ts#L43-L56)

## Handler Selection and Tie-Breaking

When multiple handlers might match a single path (e.g., via middleware or overlapping patterns), the router must determine the order of evaluation. The `RegExpRouter` uses a sorting mechanism during the build process:

```typescript
.sort(([isStaticA, pathA], [isStaticB, pathB]) =>
  isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length
)
```

This logic ensures that routes are ordered such that static routes are favored and dynamic paths are ordered by their path length, establishing a consistent priority for pattern matching.

Sources: [src/router/reg-exp-router/router.ts:L47-L49](https://github.com/blade47/hono/blob/main/src/router/reg-exp-router/router.ts#L47-L49)

## The Prepared Router

For static-heavy applications, `RegExpRouter` offers a `PreparedRegExpRouter`. This variant allows the matcher to be pre-built and serialized into a string. This is useful for environments (like cold-start serverless functions) where compiling the router at runtime would be too slow.

- `buildInitParams`: Collects path data and generates the matcher.
- `serializeInitParams`: Converts the internal matcher data into a JSON string that can be safely embedded in a source file.

```mermaid
sequenceDiagram
    participant User
    participant PRR as PreparedRegExpRouter
    participant Matcher
    User->>PRR: add(method, path, handler)
    PRR->>Matcher: Access pre-compiled regex
    Matcher-->>PRR: Return index/params
    PRR->>PRR: Update handler array
```
Sources: [src/router/reg-exp-router/prepared-router.ts:L9-L93](https://github.com/blade47/hono/blob/main/src/router/reg-exp-router/prepared-router.ts#L9-L93)

## Error Handling and Invariants

The router enforces strict path invariants during construction. If a path is malformed (e.g., illegal segments), it throws an `UnsupportedPathError`. 

> [!WARNING]
> The `RegExpRouter` expects well-formed paths. If you add a path that the `Trie` cannot represent due to internal limitations, `PATH_ERROR` will be thrown, causing the router to abort the build process.

Sources: [src/router/reg-exp-router/router.ts:L63-L65](https://github.com/blade47/hono/blob/main/src/router/reg-exp-router/router.ts#L63-L65)

## Summary of Design Trade-offs

| Design Choice | Benefit | Cost |
| :--- | :--- | :--- |
| Regex Matching | Constant time complexity for routing | Longer initial build time |
| Trie-based pre-processing | Consistent handling of params/wildcards | Higher memory footprint during build |
| Serialization (Prepared) | Near-zero cold start time | Complex setup and build-time tooling |

Sources: [src/router/reg-exp-router/router.ts:L34-L103](https://github.com/blade47/hono/blob/main/src/router/reg-exp-router/router.ts#L34-L103), [src/router/reg-exp-router/prepared-router.ts](https://github.com/blade47/hono/blob/main/src/router/reg-exp-router/prepared-router.ts)

## Related

- [Smart Router](https://www.doc0.app/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing-algorithms/smart-router)
- [Alternative Routers](https://www.doc0.app/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing-algorithms/alternative-routers)


## Sitemap

See the full [sitemap](https://www.doc0.app/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/llms.txt) for all pages in this wiki.
