Chapter 13

Organizing Routes

Split Hono apps into smaller route groups.

Organizing Routes

Small apps can keep routes in one file. As an app grows, route groups keep related behavior together.

Sub-apps

A Hono app can mount another Hono app with app.route().

import { Hono } from 'hono'

const api = new Hono()

api.get('/chapters', (c) => {
  return c.json({ chapters: [] })
})

api.get('/chapters/:slug', (c) => {
  return c.json({ slug: c.req.param('slug') })
})

app.route('/api', api)

Those routes are available at /api/chapters and /api/chapters/:slug.

Base paths

Use basePath() when you want a group to define its own prefix.

const admin = new Hono().basePath('/admin')

admin.get('/health', (c) => c.text('OK'))

app.route('/', admin)

File structure

Route groups usually map to files by feature.

src/
  index.tsx
  routes/
    api.ts
    admin.ts

Keep shared rendering, validation, and data helpers outside route files. The goal is for each route file to read like a table of contents for one area of the app.

This book is still small enough for src/index.tsx, but the chapter and rendering code are already split into separate modules.