Overview
Routing in Hono maps HTTP requests to handler functions based on the request method and URL path. Hono provides a simple and intuitive API for defining routes with full type safety.
Defining Routes
Routes are defined using HTTP method helpers on the Hono application instance. Each method corresponds to a standard HTTP verb.
Basic Route Definition
HTTP Method Handlers
Hono supports all standard HTTP methods through dedicated handler functions:
Available Methods
From src/hono-base.ts:104-110:
The all Method
The all method matches any HTTP method:
Path Patterns
Hono supports various path patterns for flexible route matching.
Static Paths
Exact path matching:
Path Parameters
Capture dynamic segments using :param syntax:
Wildcard Paths
Match multiple path segments:
The on Method
For custom methods or matching multiple methods, use the on method:
From src/hono-base.ts:144-154:
Route Grouping
Group routes with a common base path using route:
From src/hono-base.ts:208-232:
Base Paths
Define a base path for all routes in an instance:
From src/hono-base.ts:247-253:
Route Matching
Routes are matched in the order they are defined. The first matching route handles the request.
Strict Mode
By default, Hono uses strict mode which distinguishes /path from /path/:
Disable strict mode to treat both the same:
From src/hono-base.ts:46-87:
Chaining Routes
Multiple handlers can be chained on the same path:
From src/hono-base.ts:127-141, routes return the app instance for chaining:
Access registered routes through the routes property:
From src/types.ts:57-62:
Best Practices
- Define specific routes before wildcard routes
- Use route grouping for better organization
- Leverage TypeScript for path parameter type safety
- Use
basePath for API versioning
Wildcard routes (*) should be defined last, as they will match any path that hasn’t been matched by previous routes.