Overview
The Hono app uses various middleware layers to handle cross-cutting concerns like authentication, rate limiting, metrics collection, and request/response logging.Authentication Middleware
File:src/routes/middlewares/auth.ts
authContextMiddleware
Middleware that retrieves the current session and user from Better Auth and stores them in the request context. File:src/routes/middlewares/auth.ts:7-18
- Extracts session information from request headers
- Calls Better Auth API to validate and retrieve session
- Sets
userandsessionin context:- If authenticated: Sets actual user and session objects
- If not authenticated: Sets both to
null
- Continues to next middleware
c.get('user')- Current authenticated user ornullc.get('session')- Current session ornull
src/app.ts:53
Rate Limiting Middleware
File:src/routes/middlewares/rate-limit/index.ts
rateLimit
Database-backed rate limiting middleware that restricts request frequency per client. File:src/routes/middlewares/rate-limit/index.ts:15-45
-
Authenticated Users: Uses session ID
-
Anonymous Users: Uses IP address
- First tries to extract from headers (proxy headers, CloudFlare, etc.)
- Falls back to IP from Hono context
- Uses
"anonymous"if no IP can be determined
RateLimit-* headers:
RateLimit-Limit- Maximum requests allowed in windowRateLimit-Remaining- Requests remaining in current windowRateLimit-Reset- Time when the window resets
- Authenticated:
"Rate limit exceeded for your account. Please try again later." - Anonymous:
"Rate limit exceeded. Please try again later."
DbStore (see Database section below)
Usage:
DbStore
File:src/routes/middlewares/rate-limit/store.ts
PostgreSQL-backed store for rate limit hit counts using Drizzle ORM.
File: src/routes/middlewares/rate-limit/store.ts:18-22
init(options)
File:src/routes/middlewares/rate-limit/store.ts:34-37
Initializes the store with rate limiter configuration.
get(key)
File:src/routes/middlewares/rate-limit/store.ts:48-83
Retrieves a client’s current hit count and reset time.
- Queries database for rate limit record by key
- Returns
undefinedif record doesn’t exist - Automatically deletes expired records (outside window)
- Calculates reset time based on window duration
increment(key)
File:src/routes/middlewares/rate-limit/store.ts:94-150
Increments a client’s hit counter.
- Checks for existing record
- If exists and not expired: Increments count
- If exists and expired: Resets count to 1
- If doesn’t exist: Creates new record with count of 1
- Updates
lastRequesttimestamp - Returns updated hit count and reset time
decrement(key)
File:src/routes/middlewares/rate-limit/store.ts:159-172
Decrements a client’s hit counter (used when request is rejected).
- Uses SQL
GREATEST(0, count - 1)to prevent negative counts - Updates
lastRequesttimestamp - Silently fails on error (logs error)
resetKey(key)
File:src/routes/middlewares/rate-limit/store.ts:181-187
Resets a specific client’s hit counter.
resetAll()
File:src/routes/middlewares/rate-limit/store.ts:194-200
Resets all clients’ hit counters.
rate_limit table
shutdown()
File:src/routes/middlewares/rate-limit/store.ts:208-210
Cleanup method for interface compatibility.
Metrics Middleware
File:src/routes/middlewares/metrics.ts
metricsMiddleware
DEPRECATED: The@hono/otel middleware already provides built-in metrics.
File: src/routes/middlewares/metrics.ts:49-83
Records HTTP request metrics using OpenTelemetry.
http_request_duration_metric
Histogram of request response times in milliseconds. File:src/routes/middlewares/metrics.ts:13-20
method- HTTP method (GET, POST, etc.)route- Request route/pathstatus_code- HTTP status code (200, 404, etc.)status_class- Status code class (2xx, 4xx, etc.)
http_requests_total_metric
Counter of total HTTP requests. File:src/routes/middlewares/metrics.ts:23-25
method- HTTP methodroute- Request route/path
- Records start time using
performance.now() - Increments request counter with method and route labels
- Executes next middleware
- Calculates response time
- Records response time histogram with all labels
@hono/otel middleware instead (configured in src/app.ts:35-38)
Request/Response Logger
File:src/routes/middlewares/req-res-logger.ts
reqResLogger
Development middleware for logging request and response bodies. File:src/routes/middlewares/req-res-logger.ts:23-55
-
Request Logging:
- Clones the request to read body without consuming it
- Logs incoming request body with
<-- [Incoming Body]prefix - Attempts to prettify JSON for readability
- Logs raw text if not valid JSON
-
Response Logging:
- Clones the response after handler execution
- Logs outgoing response body with
--> [Outgoing Body]prefix - Attempts to prettify JSON for readability
- Logs raw text if not valid JSON
src/routes/middlewares/req-res-logger.ts:8-16
src/app.ts:44
Use Cases:
- Debugging API payloads
- Monitoring request/response structure
- Development troubleshooting
Global Middleware Stack
File:src/app.ts:29-65
The following middleware is applied globally to all routes in order:
httpInstrumentationMiddleware- OpenTelemetry instrumentationcontextStorage- AsyncLocalStorage for contextloggerMiddleware- Request loggingcors- Cross-origin resource sharingrequestId- Unique request ID generationauthContextMiddleware- Authentication contexttiming- Server-Timing headertimeout- Request timeout (15 seconds)languageDetector- Language preference detectioncsrf- CSRF protectionsecureHeaders- Security headersprettyJSON- JSON pretty printing
