Kind: Function
Source: src/middleware/body-limit/index.ts
Part of: Middleware
Body Limit Middleware for Hono.
bodyLimit creates Hono middleware that checks incoming request bodies against a configured maximum size. Requests that exceed the limit are handled by the middleware error path, while allowed requests continue to the next middleware or route handler.
Signature
tsfunction bodyLimit(options: BodyLimitOptions): MiddlewareHandler
Parameters
| Name | Type |
|---|---|
options | BodyLimitOptions |
Returns: MiddlewareHandler
Diagram
mermaidgraph LR Client[Client] --> Request[Incoming request] Request --> Limit[bodyLimit middleware] Limit -->|Within configured size| Next[Next middleware or route] Limit -->|Exceeds configured size| Error[Error handler]
Usage
tsimport { Hono } from 'hono'
import { bodyLimit } from 'hono/body-limit'
const app = new Hono()
const maxBodySize = Number(process.env.MAX_BODY_SIZE)
app.use(
'/uploads/*',
bodyLimit({
maxSize: maxBodySize,
})
)
app.post('/uploads', async (c) => {
const body = await c.req.arrayBuffer()
return c.json({
receivedBytes: body.byteLength,
})
})
AI Coding Instructions
- Register
bodyLimitbefore routes or middleware that read the request body. - Set
maxSizefrom validated application configuration in bytes. - Do not rely only on the
Content-Lengthheader; streamed request data is also checked. - Use the
onErroroption when the application needs a custom response for oversized bodies.
Was this page helpful?