Getting Started
Core Concepts
Built-In Middleware
Advanced Features
Troubleshooting
Utility middleware provides standard tools to enhance your application's request handling, such as logging traffic, compressing responses, and managing request payloads. These components are designed to be "plug-and-play," allowing you to add functionality to your routes with minimal configuration.
The logger middleware prints request and response details to your console, including the HTTP method, request path, status code, and response time.
Usage:
import { logger } from 'hono/logger'
const app = new Hono()
app.use(logger())You can customize the output by passing a printing function (default is console.log):
app.use(logger((message) => {
// Custom logging logic (e.g., sending to a service)
console.log(`[LOG]: ${message}`)
}))The bodyLimit middleware prevents your server from processing requests that are too large, helping to protect against memory exhaustion or malicious uploads.
Usage:
import { bodyLimit } from 'hono/body-limit'
app.post(
'/upload',
bodyLimit({
maxSize: 50 * 1024, // 50kb
onError: (c) => c.text('Payload too large', 413),
}),
async (c) => {
// Handler logic...
}
)Warning
If a request exceeds the maxSize, the middleware will trigger the onError handler (or throw a 413 error by default) and stop the request from reaching your route handler.
The compress middleware automatically shrinks your response body using gzip or deflate algorithms, which can significantly improve performance for text-based content.
Usage:
import { compress } from 'hono/compress'
const app = new Hono()
app.use(compress())Tip
The compression middleware automatically transforms strong ETags into weak ETags (W/), as compressed data is not byte-identical to the original uncompressed source.
next() function is called to pass control to the subsequent middleware or route handler in the stack.bodyLimit middleware handles these cases by buffering and measuring the incoming data.Note
The compress middleware will not compress responses if the Cache-Control header contains no-transform, following standard HTTP best practices.