Chapter 12
Built-in Middleware
Add common behavior with Hono's included middleware.
Built-in Middleware
Middleware lets you add behavior around routes. Hono includes middleware for common web application needs.
Logging and security
Start with middleware that applies broadly.
import { logger } from 'hono/logger'
import { secureHeaders } from 'hono/secure-headers'
app.use(logger())
app.use(secureHeaders())
logger() helps during development and operations. secureHeaders() adds common security headers to responses.
CORS
Use CORS when browsers need to call your API from another origin.
import { cors } from 'hono/cors'
app.use(
'/api/*',
cors({
origin: 'https://example.com',
})
)
Keep CORS scoped to the routes that need browser access from another site.
Cache helpers
ETag and cache middleware can reduce repeated work.
import { etag } from 'hono/etag'
app.use(etag())
For a mostly static book like this one, caching middleware can be useful around rendered pages and chapter responses.
Basic Auth
Basic Auth is useful for small private areas or previews.
import { basicAuth } from 'hono/basic-auth'
app.use(
'/admin/*',
basicAuth({
username: 'admin',
password: 'secret',
})
)
Middleware order matters. Register broad middleware first, then add route-specific middleware closer to the routes that need it.