Skip to main content

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

Static Routes

O(1) - Direct hash map lookup

Dynamic Routes

O(1) - Single RegExp match

Build Time

O(n log n) - Routes sorted and compiled once

Memory

High - Precompiled matchers cached in memory

When to Use

  • 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

Configuration

The RegExpRouter is used by default in Hono and requires no configuration:
To explicitly specify the router:

Usage Examples

Basic Routing

Route Parameters with Patterns

Optional Parameters

Wildcard Routes

Performance Optimization

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:

Middleware Integration

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

Limitations

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)

Unsupported Path Examples

Internal Architecture

Build Process

Match Process

Comparison with Other Routers

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

SmartRouter

Automatically selects the best router for your routes

TrieRouter

Tree-based router supporting all path patterns

Routing Guide

Learn about choosing the right router

Performance Guide

Optimize your Hono application