Request Limit Plugin
Restrict the size of incoming request bodies with RequestLimitHandlerPlugin to protect your server from oversized payloads.
Setup
Use RequestLimitHandlerPlugin to limit the size of incoming request bodies.
import { RequestLimitHandlerPlugin } from '@orpc/server/plugins'
const handler = new RPCHandler(router, {
plugins: [
new RequestLimitHandlerPlugin({
/**
* The maximum allowed request body size in bytes.
*/
maxBodySize: 1024 * 1024, // 1MB
}),
],
})
Custom Error
By default the plugin throws PAYLOAD_TOO_LARGE. Use error to throw your own, which is defined when its code and data match an error the matched procedure declares. A custom code responds with 400 unless you map it in errorStatusMap.
new RequestLimitHandlerPlugin({
maxBodySize: 1024 * 1024,
error: () => new ORPCError('TOO_BIG'),
})
Peer Adapters
This plugin does not apply to peer-based adapters such as WebSocket and Message Port. Each message reaches the handler fully loaded in memory, so there is no body left to limit. Instead, limit each message at the transport, and the total bytes per connection per minute, since a single call can span many messages (for example, an AsyncIteratorObject input). With Bun:
const MAX_BYTES_PER_MINUTE = 10 * 1024 * 1024 // 10MB
const usage = new WeakMap<object, { bytes: number; resetAt: number }>()
Bun.serve({
websocket: {
maxPayloadLength: 1024 * 1024, // 1MB per message, larger messages close the connection
async message(ws, message) {
let entry = usage.get(ws)
if (!entry || Date.now() >= entry.resetAt) {
usage.set(ws, (entry = { bytes: 0, resetAt: Date.now() + 60_000 }))
}
entry.bytes += Buffer.byteLength(message)
if (entry.bytes > MAX_BYTES_PER_MINUTE) {
ws.close(1008, 'Too much data per minute')
return
}
await handler.message(ws, message)
},
async close(ws) {
await handler.close(ws)
},
},
})
Other WebSocket servers have an equivalent per-message option, such as maxPayload in ws.
Learn More
For implementation details, see the source code.