$ cat docs/middleware/body-limit.md
Body limitLimite de corpo
Set a smaller body limit per route, counting the bytes that really arrive.Defina um limite de corpo menor por rota, contando os bytes que realmente chegam.
What it doesO que faz
bodyLimit(options: BodyLimitOptions): MiddlewareHandler. It rejects by content-length first, then counts streamed bytes on a clone, so a missing or lying length cannot bypass it. The handler still reads ctx.req, and getRawBody(ctx) returns the bytes already read.
bodyLimit(options: BodyLimitOptions): MiddlewareHandler. Ele recusa primeiro pelo content-length, depois conta os bytes transmitidos em um clone, então um tamanho ausente ou falso não escapa. O handler continua lendo ctx.req, e getRawBody(ctx) devolve os bytes já lidos.
Install and orderInstalar e ordenar
pnpm add @tupik/middleware The engine already applies createApp({ bodyLimit }) (1 MiB) to JSON bodies before middleware; use this one for smaller per-route limits and for non-JSON bodies (uploads, form data, raw text).
O engine já aplica createApp({ bodyLimit }) (1 MiB) a corpos JSON antes dos middlewares; use este para limites menores por rota e para corpos não JSON (uploads, formulários, texto cru).
ExampleExemplo
import { createModule } from '@tupik/core';
import { bodyLimit, getRawBody } from '@tupik/middleware';
const uploads = createModule('/upload')
.use(bodyLimit({ maxBytes: 64 * 1024 })) // 413 PAYLOAD_TOO_LARGE above 64 KiB
.post('/avatar', { access: 'authenticated', handler: (ctx) => ({ size: getRawBody(ctx)?.byteLength }) });import { createModule } from '@tupik/core';
import { bodyLimit, getRawBody } from '@tupik/middleware';
const uploads = createModule('/upload')
.use(bodyLimit({ maxBytes: 64 * 1024 })) // 413 PAYLOAD_TOO_LARGE acima de 64 KiB
.post('/avatar', { access: 'authenticated', handler: (ctx) => ({ size: getRawBody(ctx)?.byteLength }) }); APIAPI
| OptionOpção | TypeTipo | Default / behaviorPadrão / comportamento |
|---|---|---|
maxBytes | number | Required. Largest accepted body in bytes (integer ≥ 0).Obrigatório. Maior corpo aceito em bytes (inteiro ≥ 0). |
interface BodyLimitOptions { maxBytes: number }
interface BodyLimitOptions { maxBytes: number }
Errors and limitsErros e limites
- Over the limit:
413 PAYLOAD_TOO_LARGE(RFC 9457) and the handler is not called. - A negative or non-integer
maxBytesthrows at creation. - Accepted bodies are buffered in memory (up to
maxBytes) so the handler can read them again.
- Acima do limite:
413 PAYLOAD_TOO_LARGE(RFC 9457) e o handler não é chamado. maxBytesnegativo ou não inteiro lança na criação.- Corpos aceitos ficam em memória (até
maxBytes) para o handler ler de novo.
When not to use itQuando não usar
For large uploads, stream straight to storage (R2, S3) with your own byte counting instead of buffering here.
Para uploads grandes, transmita direto para o storage (R2, S3) com a sua contagem de bytes em vez de bufferizar aqui.