> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/honojs/hono/llms.txt
> Use this file to discover all available pages before exploring further.

# RegExpRouter

> High-performance router using trie-based RegExp compilation for optimal routing speed

## Overview

The `RegExpRouter` is Hono's default and most performant router implementation. It uses a sophisticated trie-based algorithm to compile all routes into a single optimized regular expression, eliminating linear loops entirely.

## How It Works

The RegExpRouter employs a two-phase approach:

1. **Build Phase**: Routes are organized into a trie structure, with static paths separated from dynamic routes
2. **Compilation Phase**: The trie is compiled into a highly optimized RegExp with indexed capture groups
3. **Match Phase**: Path matching is performed using a single RegExp execution, making it O(1) for static routes

### Algorithm Details

* Uses a `Trie` data structure to organize routes hierarchically
* Static routes are stored in a hash map for instant O(1) lookup
* Dynamic routes are compiled into a single RegExp with numbered capture groups
* Parameter extraction uses pre-calculated index maps for maximum performance
* Wildcard middleware patterns are cached and tested separately

## Performance Characteristics

<CardGroup cols={2}>
  <Card title="Static Routes" icon="gauge-high">
    **O(1)** - Direct hash map lookup
  </Card>

  <Card title="Dynamic Routes" icon="bolt">
    **O(1)** - Single RegExp match
  </Card>

  <Card title="Build Time" icon="clock">
    **O(n log n)** - Routes sorted and compiled once
  </Card>

  <Card title="Memory" icon="memory">
    **High** - Precompiled matchers cached in memory
  </Card>
</CardGroup>

## When to Use

<AccordionGroup>
  <Accordion title="✅ Best For">
    * Production applications requiring maximum performance
    * Applications with many routes (100+)
    * Static routes with occasional dynamic parameters
    * Edge computing environments (Cloudflare Workers, Deno Deploy)
    * When route registration happens once at startup
  </Accordion>

  <Accordion title="❌ Not Recommended For">
    * Applications with constantly changing routes at runtime
    * Routes with duplicate parameter names in different positions
    * Complex nested parameter patterns
    * Routes combining wildcards with parameters (`:param/*`)
  </Accordion>
</AccordionGroup>

## Configuration

The RegExpRouter is used by default in Hono and requires no configuration:

```typescript theme={null}
import { Hono } from 'hono'

const app = new Hono() // Uses RegExpRouter by default
```

To explicitly specify the router:

```typescript theme={null}
import { Hono } from 'hono'
import { RegExpRouter } from 'hono/router/reg-exp-router'

const app = new Hono({ router: new RegExpRouter() })
```

## Usage Examples

### Basic Routing

```typescript theme={null}
import { Hono } from 'hono'

const app = new Hono()

// Static routes (O(1) lookup)
app.get('/', (c) => c.text('Home'))
app.get('/about', (c) => c.text('About'))
app.get('/contact', (c) => c.text('Contact'))

// Dynamic routes
app.get('/users/:id', (c) => {
  const id = c.req.param('id')
  return c.json({ userId: id })
})

// Nested parameters
app.get('/posts/:postId/comments/:commentId', (c) => {
  const { postId, commentId } = c.req.param()
  return c.json({ postId, commentId })
})
```

### Route Parameters with Patterns

```typescript theme={null}
// Match numeric IDs only
app.get('/users/:id{[0-9]+}', (c) => {
  const id = c.req.param('id')
  return c.json({ userId: id })
})

// Match file extensions
app.get('/files/:filename{.+\\.(jpg|png|gif)}', (c) => {
  const filename = c.req.param('filename')
  return c.json({ file: filename })
})
```

### Optional Parameters

```typescript theme={null}
// Optional trailing segment
app.get('/api/v1/users/:id?', (c) => {
  const id = c.req.param('id')
  return c.json({ id: id || 'all' })
})
```

### Wildcard Routes

```typescript theme={null}
// Catch-all route
app.get('/static/*', (c) => {
  return c.text('Static file handler')
})

// Wildcard middleware
app.use('/api/*', async (c, next) => {
  console.log('API request:', c.req.path)
  await next()
})
```

### Performance Optimization

```typescript theme={null}
import { Hono } from 'hono'

const app = new Hono()

// Group static routes together for optimal hash map performance
app.get('/', (c) => c.text('Home'))
app.get('/about', (c) => c.text('About'))
app.get('/contact', (c) => c.text('Contact'))
app.get('/pricing', (c) => c.text('Pricing'))

// Dynamic routes are compiled into a single RegExp
app.get('/users/:id', (c) => c.json({ id: c.req.param('id') }))
app.get('/posts/:slug', (c) => c.json({ slug: c.req.param('slug') }))
app.get('/categories/:name', (c) => c.json({ name: c.req.param('name') }))
```

## Advanced Features

### Method-Specific Matchers

The RegExpRouter builds separate matchers for each HTTP method, optimizing for the most common case where different methods have different route structures:

```typescript theme={null}
// Each method gets its own optimized matcher
app.get('/users/:id', getUser)
app.post('/users', createUser)
app.put('/users/:id', updateUser)
app.delete('/users/:id', deleteUser)
```

### Middleware Integration

Wildcard middleware is intelligently applied to routes during the build phase:

```typescript theme={null}
// Middleware is attached to routes at build time
app.use('/api/*', authMiddleware)

// These routes will include authMiddleware
app.get('/api/users', listUsers)
app.get('/api/posts', listPosts)
```

## Limitations

<Warning>
  The RegExpRouter has some path restrictions:

  * **No duplicate parameter names** in the same route at different levels
  * **No wildcard + parameter combinations** like `/path/:param/*`
  * **Ambiguous routes throw errors** during compilation
  * Routes cannot be added after the first match (matchers are built lazily)
</Warning>

### Unsupported Path Examples

```typescript theme={null}
// ❌ Duplicate parameter names
app.get('/:user/posts/:user', handler) // Will throw UnsupportedPathError

// ❌ Wildcard with parameter
app.get('/files/:name/*', handler) // Will throw UnsupportedPathError

// ❌ Ambiguous routes
app.get('/:a/b', handler1)
app.get('/a/:b', handler2) // May throw during match
```

## Internal Architecture

### Build Process

```typescript theme={null}
// Conceptual build flow
1. Routes collected during app.get(), app.post(), etc.
2. On first match() call:
   a. Routes sorted by static vs dynamic
   b. Static routes stored in hash map
   c. Dynamic routes inserted into trie
   d. Trie compiled to RegExp
   e. Capture group indices mapped to parameters
3. Compiled matchers cached for subsequent requests
```

### Match Process

```typescript theme={null}
// Conceptual match flow
1. Check static map: O(1) lookup
2. If not found, execute compiled RegExp: O(1) match
3. Extract capture groups using index map
4. Return handlers with parameters
```

## Comparison with Other Routers

| Feature                | RegExpRouter | TrieRouter | LinearRouter |
| ---------------------- | ------------ | ---------- | ------------ |
| Static routes          | O(1)         | O(n)       | O(n)         |
| Dynamic routes         | O(1)         | O(n)       | O(n)         |
| Memory usage           | High         | Medium     | Low          |
| Build complexity       | High         | Low        | None         |
| All patterns supported | No           | Yes        | Yes          |

## Source Code Reference

The RegExpRouter implementation can be found at:

* Router: `src/router/reg-exp-router/router.ts`
* Trie: `src/router/reg-exp-router/trie.ts`
* Matcher: `src/router/reg-exp-router/matcher.ts`

## See Also

<CardGroup cols={2}>
  <Card title="SmartRouter" icon="brain" href="/api/routers/smart-router">
    Automatically selects the best router for your routes
  </Card>

  <Card title="TrieRouter" icon="tree" href="/api/routers/trie-router">
    Tree-based router supporting all path patterns
  </Card>

  <Card title="Routing Guide" icon="route" href="/routing/routers">
    Learn about choosing the right router
  </Card>

  <Card title="Performance Guide" icon="gauge-high" href="/guides/performance">
    Optimize your Hono application
  </Card>
</CardGroup>
