# PatternRouter

**Kind:** Class

**Source:** [`src/router/pattern-router/router.ts`](https://github.com/honojs/hono/blob/main/src/router/pattern-router/router.ts#L8)

**Part of:** [Router](subsystem-src-router)

`PatternRouter` stores handlers or values under path patterns and resolves an incoming path against those patterns. Call `add()` to register a pattern, then call `match()` to receive a `Result<T>` for the matching route.

**Implements:** `Router`

## Methods

| Method | Signature | Returns |
|---|---|---|
| `add` | `add(method: string, path: string, handler: T)` | `void` |
| `match` | `match(method: string, path: string)` | `Result<T>` |

## Properties

| Property | Type |
|---|---|
| `name` | `string` |
| `#routes` | `Route<T>[]` |

## When something fails

- `PatternRouter` handles failure in 1 place: it lets it reach the caller in all 1.

## Diagram

```mermaid
graph LR
  A[Pattern and value] --> B[PatternRouter.add]
  C[Incoming path] --> D[PatternRouter.match]
  B --> E[Registered patterns]
  E --> D
  D --> F[Result<T>]
```

## Usage

```ts
import { PatternRouter } from './router';

const router = new PatternRouter<string>();

router.add('/users/:id', 'user-detail');
router.add('/posts/:slug', 'post-detail');

const result = router.match('/users/42');

console.log(result);
```

## AI Coding Instructions

- Register patterns through `add()` before attempting to resolve paths with `match()`.
- Keep the value type consistent with the router generic, such as `PatternRouter<string>` or `PatternRouter<RouteHandler>`.
- Treat the return value from `match()` as a `Result<T>` and handle both matching and non-matching outcomes.
- Keep pattern syntax consistent across registrations so route parameters are parsed predictably.

## Relationships

- IMPORTS → `METHOD_NAME_ALL`
- IMPORTS → `UnsupportedPathError`
