> ## 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.

# Hono

> The main Hono class for creating web applications

# 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.

```typescript theme={null}
const app = new Hono<E, S, BasePath>(options?)
```

<ParamField path="options" type="HonoOptions<E>" optional>
  Configuration options for the Hono instance

  <Expandable title="properties">
    <ParamField path="strict" type="boolean" default="true">
      Specifies whether to distinguish whether the last path is a directory or not. When `true`, `/about` and `/about/` are treated as different routes.
    </ParamField>

    <ParamField path="router" type="Router<[H, RouterRoute]>" optional>
      Custom router implementation. By default, Hono uses `SmartRouter` with `RegExpRouter` and `TrieRouter`.
    </ParamField>

    <ParamField path="getPath" type="GetPath<E>" optional>
      Custom function to extract the path from a request. Useful for handling host header routing.
    </ParamField>
  </Expandable>
</ParamField>

### Type Parameters

<ParamField path="E" type="Env" default="BlankEnv">
  Environment type that defines bindings and variables available in your app
</ParamField>

<ParamField path="S" type="Schema" default="BlankSchema">
  Schema type that defines your API routes for type-safe client generation
</ParamField>

<ParamField path="BasePath" type="string" default="'/'">
  Base path prefix for all routes in this app instance
</ParamField>

### Example

```typescript theme={null}
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.

```typescript theme={null}
app.get(path, ...handlers)
app.get(...handlers)
```

<ParamField path="path" type="string" optional>
  The route path. If omitted, handlers are applied to the current path.
</ParamField>

<ParamField path="handlers" type="Handler[]" required>
  One or more handler functions or middleware
</ParamField>

<ResponseField name="return" type="Hono">
  Returns the Hono instance for method chaining
</ResponseField>

```typescript theme={null}
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.

```typescript theme={null}
app.post(path, ...handlers)
```

```typescript theme={null}
app.post('/users', async (c) => {
  const body = await c.req.json()
  return c.json({ created: true, data: body })
})
```

### put

Register a PUT route handler.

```typescript theme={null}
app.put(path, ...handlers)
```

### delete

Register a DELETE route handler.

```typescript theme={null}
app.delete(path, ...handlers)
```

### patch

Register a PATCH route handler.

```typescript theme={null}
app.patch(path, ...handlers)
```

### options

Register an OPTIONS route handler.

```typescript theme={null}
app.options(path, ...handlers)
```

### all

Register a route handler that matches all HTTP methods.

```typescript theme={null}
app.all(path, ...handlers)
```

```typescript theme={null}
app.all('/status', (c) => c.text('OK'))
```

## Middleware Methods

### use

Register middleware that runs for matching routes.

```typescript theme={null}
app.use(path?, ...middleware)
```

<ParamField path="path" type="string" optional>
  Path pattern to match. Defaults to `'*'` (all routes).
</ParamField>

<ParamField path="middleware" type="MiddlewareHandler[]" required>
  One or more middleware functions
</ParamField>

<ResponseField name="return" type="Hono">
  Returns the Hono instance for method chaining
</ResponseField>

```typescript theme={null}
// 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.

```typescript theme={null}
app.on(method, path, ...handlers)
```

<ParamField path="method" type="string | string[]" required>
  HTTP method(s) to match
</ParamField>

<ParamField path="path" type="string | string[]" required>
  Path(s) to match
</ParamField>

<ParamField path="handlers" type="Handler[]" required>
  Route handlers
</ParamField>

<ResponseField name="return" type="Hono">
  Returns the Hono instance for method chaining
</ResponseField>

```typescript theme={null}
// 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.

```typescript theme={null}
app.route(path, subApp)
```

<ParamField path="path" type="string" required>
  Base path for the sub-application
</ParamField>

<ParamField path="subApp" type="Hono" required>
  The Hono instance to mount
</ParamField>

<ResponseField name="return" type="Hono">
  Returns the Hono instance with merged routes
</ResponseField>

```typescript theme={null}
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.

```typescript theme={null}
app.basePath(path)
```

<ParamField path="path" type="string" required>
  Base path prefix to add
</ParamField>

<ResponseField name="return" type="Hono">
  Returns a new Hono instance with the base path applied
</ResponseField>

```typescript theme={null}
const api = new Hono().basePath('/api/v1')
api.get('/users', handler) // Matches /api/v1/users
```

### mount

Mount applications built with other frameworks.

```typescript theme={null}
app.mount(path, applicationHandler, options?)
```

<ParamField path="path" type="string" required>
  Base path for the mounted application
</ParamField>

<ParamField path="applicationHandler" type="(request: Request, ...args: any) => Response | Promise<Response>" required>
  Request handler from another framework
</ParamField>

<ParamField path="options" type="MountOptions" optional>
  Configuration for how the request should be handled
</ParamField>

<ResponseField name="return" type="Hono">
  Returns the Hono instance for method chaining
</ResponseField>

```typescript theme={null}
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.

```typescript theme={null}
app.onError(handler)
```

<ParamField path="handler" type="ErrorHandler<E>" required>
  Function that receives an error and context, returns a Response
</ParamField>

<ResponseField name="return" type="Hono">
  Returns the Hono instance for method chaining
</ResponseField>

```typescript theme={null}
app.onError((err, c) => {
  console.error(`${err}`)
  return c.text('Custom Error Message', 500)
})
```

### notFound

Register a custom 404 handler.

```typescript theme={null}
app.notFound(handler)
```

<ParamField path="handler" type="NotFoundHandler<E>" required>
  Function that receives a context and returns a Response
</ParamField>

<ResponseField name="return" type="Hono">
  Returns the Hono instance for method chaining
</ResponseField>

```typescript theme={null}
app.notFound((c) => {
  return c.text('Custom 404 Message', 404)
})
```

## Request Handling

### fetch

The main entry point for handling requests.

```typescript theme={null}
app.fetch(request, env?, executionCtx?)
```

<ParamField path="request" type="Request" required>
  The incoming Request object
</ParamField>

<ParamField path="env" type="E['Bindings']" optional>
  Environment bindings (e.g., Cloudflare Workers bindings)
</ParamField>

<ParamField path="executionCtx" type="ExecutionContext" optional>
  Execution context for async operations
</ParamField>

<ResponseField name="return" type="Response | Promise<Response>">
  The response to send back to the client
</ResponseField>

```typescript theme={null}
// Cloudflare Workers
export default app

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

### request

Convenience method for testing that creates a Request and calls fetch.

```typescript theme={null}
app.request(input, requestInit?, env?, executionCtx?)
```

<ParamField path="input" type="Request | string | URL" required>
  Request object, URL string, or pathname
</ParamField>

<ParamField path="requestInit" type="RequestInit" optional>
  Request initialization options
</ParamField>

<ParamField path="env" type="E['Bindings']" optional>
  Environment bindings
</ParamField>

<ParamField path="executionCtx" type="ExecutionContext" optional>
  Execution context
</ParamField>

<ResponseField name="return" type="Response | Promise<Response>">
  The response from the application
</ResponseField>

```typescript theme={null}
// 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.

```typescript theme={null}
app.routes: RouterRoute[]
```

```typescript theme={null}
console.log(app.routes)
// [{ path: '/', method: 'GET', handler: [Function] }, ...]
```
