Skip to main content

Overview

Handlers are functions that process HTTP requests and return responses. In Hono, every route is associated with one or more handler functions.

Handler Types

Hono defines two main handler types:

Handler

A standard request handler that returns a response: From src/types.ts:76-81:

MiddlewareHandler

A middleware-style handler that must call next() or return a response: From src/types.ts:83-88:

Combined Handler Type

The H type represents either a Handler or MiddlewareHandler: From src/types.ts:90-95:

Handler Signature

All handlers receive two parameters:
  1. Context (c): Provides access to request/response data and utilities
  2. Next (next): Function to pass control to the next handler

Handler Response Types

Handlers can return various response types: From src/types.ts:70-74:

Returning Responses

Synchronous Response

Asynchronous Response

Raw Response Object

Basic Handler Examples

Simple GET Handler

POST Handler with JSON

Handler with Path Parameters

Handler with Query Parameters

Multiple Handlers

Routes can have multiple handlers that execute in sequence:

Type-Safe Handlers

Define environment and input types for type safety:

Error Handling

Throwing Errors

Handlers can throw errors that are caught by the error handler:

Try-Catch in Handlers

Error Handler Types

From src/types.ts:113-119:

Async Handlers

All async operations should use async/await:

Streaming Responses

Handlers can return streaming responses:

Handler Registration

From src/hono-base.ts:385-391, handlers are added to routes:

Handler Execution

From src/hono-base.ts:423-442, handlers are executed:

Handler Context Passing

Pass data between handlers using context variables:

Not Found Handler

Customize the 404 handler:
From src/types.ts:107-111:

Custom Error Handler

Define a global error handler:
From src/hono-base.ts:35-42:

Best Practices

  • Always return a response from handlers
  • Use async/await for asynchronous operations
  • Throw HTTPException for HTTP errors with status codes
  • Use TypeScript to define environment and variable types
  • Keep handlers focused on a single responsibility
  • Use middleware for cross-cutting concerns
Handlers should always return a Response object. If a handler doesn’t return anything, Hono will throw an error: “Context is not finalized. Did you forget to return a Response object?”

Common Patterns

CRUD Operations

File Upload Handler

Pagination Handler