Skip to main content

Hono

The Hono class is the main entry point for creating Hono web applications. It extends HonoBase and provides routing, middleware, and request handling capabilities.

Constructor

Creates a new Hono application instance.
const app = new Hono<E, S, BasePath>(options?)
options
HonoOptions<E>
Configuration options for the Hono instance

Type Parameters

E
Env
default:"BlankEnv"
Environment type that defines bindings and variables available in your app
S
Schema
default:"BlankSchema"
Schema type that defines your API routes for type-safe client generation
BasePath
string
default:"'/'"
Base path prefix for all routes in this app instance

Example

import { Hono } from 'hono'
import { RegExpRouter } from 'hono/router/reg-exp-router'

// Basic usage
const app = new Hono()

// With custom router
const app2 = new Hono({ router: new RegExpRouter() })

// With strict mode disabled
const app3 = new Hono({ strict: false })

// With type definitions
type Env = {
  Bindings: {
    DB: D1Database
  }
  Variables: {
    user: User
  }
}

const app4 = new Hono<Env>()

Route Methods

Define HTTP route handlers for specific methods.

get

Register a GET route handler.
app.get(path, ...handlers)
app.get(...handlers)
path
string
The route path. If omitted, handlers are applied to the current path.
handlers
Handler[]
required
One or more handler functions or middleware
return
Hono
Returns the Hono instance for method chaining
app.get('/', (c) => c.text('Hello, World!'))

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

post

Register a POST route handler.
app.post(path, ...handlers)
app.post('/users', async (c) => {
  const body = await c.req.json()
  return c.json({ created: true, data: body })
})

put

Register a PUT route handler.
app.put(path, ...handlers)

delete

Register a DELETE route handler.
app.delete(path, ...handlers)

patch

Register a PATCH route handler.
app.patch(path, ...handlers)

options

Register an OPTIONS route handler.
app.options(path, ...handlers)

all

Register a route handler that matches all HTTP methods.
app.all(path, ...handlers)
app.all('/status', (c) => c.text('OK'))

Middleware Methods

use

Register middleware that runs for matching routes.
app.use(path?, ...middleware)
path
string
Path pattern to match. Defaults to '*' (all routes).
middleware
MiddlewareHandler[]
required
One or more middleware functions
return
Hono
Returns the Hono instance for method chaining
// Apply to all routes
app.use(logger())

// Apply to specific path
app.use('/api/*', async (c, next) => {
  c.set('requestTime', Date.now())
  await next()
})

// Multiple middleware
app.use('/admin/*', auth(), checkPermissions())

on

Register a route handler for custom HTTP methods or multiple methods.
app.on(method, path, ...handlers)
method
string | string[]
required
HTTP method(s) to match
path
string | string[]
required
Path(s) to match
handlers
Handler[]
required
Route handlers
return
Hono
Returns the Hono instance for method chaining
// Single method and path
app.on('PURGE', '/cache', (c) => c.text('Cache purged'))

// Multiple methods
app.on(['PUT', 'PATCH'], '/data', handler)

// Multiple paths
app.on('GET', ['/v1/users', '/v2/users'], handler)

Application Methods

route

Mount another Hono instance as a sub-application.
app.route(path, subApp)
path
string
required
Base path for the sub-application
subApp
Hono
required
The Hono instance to mount
return
Hono
Returns the Hono instance with merged routes
const api = new Hono()
api.get('/users', (c) => c.json({ users: [] }))
api.get('/posts', (c) => c.json({ posts: [] }))

const app = new Hono()
app.route('/api', api)
// Routes: GET /api/users, GET /api/posts

basePath

Create a new instance with a base path prefix.
app.basePath(path)
path
string
required
Base path prefix to add
return
Hono
Returns a new Hono instance with the base path applied
const api = new Hono().basePath('/api/v1')
api.get('/users', handler) // Matches /api/v1/users

mount

Mount applications built with other frameworks.
app.mount(path, applicationHandler, options?)
path
string
required
Base path for the mounted application
applicationHandler
(request: Request, ...args: any) => Response | Promise<Response>
required
Request handler from another framework
options
MountOptions
Configuration for how the request should be handled
return
Hono
Returns the Hono instance for method chaining
import { Router as IttyRouter } from 'itty-router'

const ittyRouter = IttyRouter()
ittyRouter.get('/hello', () => new Response('Hello from itty-router'))

const app = new Hono()
app.mount('/itty-router', ittyRouter.handle)

Error Handling

onError

Register a custom error handler.
app.onError(handler)
handler
ErrorHandler<E>
required
Function that receives an error and context, returns a Response
return
Hono
Returns the Hono instance for method chaining
app.onError((err, c) => {
  console.error(`${err}`)
  return c.text('Custom Error Message', 500)
})

notFound

Register a custom 404 handler.
app.notFound(handler)
handler
NotFoundHandler<E>
required
Function that receives a context and returns a Response
return
Hono
Returns the Hono instance for method chaining
app.notFound((c) => {
  return c.text('Custom 404 Message', 404)
})

Request Handling

fetch

The main entry point for handling requests.
app.fetch(request, env?, executionCtx?)
request
Request
required
The incoming Request object
env
E['Bindings']
Environment bindings (e.g., Cloudflare Workers bindings)
executionCtx
ExecutionContext
Execution context for async operations
return
Response | Promise<Response>
The response to send back to the client
// Cloudflare Workers
export default app

// Or manually
export default {
  fetch: app.fetch
}

request

Convenience method for testing that creates a Request and calls fetch.
app.request(input, requestInit?, env?, executionCtx?)
input
Request | string | URL
required
Request object, URL string, or pathname
requestInit
RequestInit
Request initialization options
env
E['Bindings']
Environment bindings
executionCtx
ExecutionContext
Execution context
return
Response | Promise<Response>
The response from the application
// For testing
test('GET /hello is ok', async () => {
  const res = await app.request('/hello')
  expect(res.status).toBe(200)
})

// With full URL
const res = await app.request('http://localhost:8787/api/users')

// With request options
const res = await app.request('/api/users', {
  method: 'POST',
  body: JSON.stringify({ name: 'John' })
})

Properties

routes

Array of all registered routes.
app.routes: RouterRoute[]
console.log(app.routes)
// [{ path: '/', method: 'GET', handler: [Function] }, ...]