Registry Mirror
Skip to content

‎apps/content/docs/helpers/ratelimit.mdx‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,19 @@ const result = await call(procedure, { email: 'user@example.com' }, { context: {
9393
When the same `limiter` and `key` combination is used multiple times in a single request chain, the `ratelimit` middleware performs the rate limit check only once. This behavior follows the [Dedupe Middleware](/docs/recipes/dedupe-middleware) recipe. To disable deduplication, set `dedupe: false`.
9494
:::
9595

96+
:::tip[Custom Error]
97+
By default the middleware throws `TOO_MANY_REQUESTS`. Use `error` to throw your own, which is [defined](/docs/error-handling#orpcerror-compatibility) when its `code` and `data` match an error the procedure declares. A custom code responds with `400` unless you map it in [`errorStatusMap`](/docs/rpc/handler#custom-error-response).
98+
99+
```ts
100+
ratelimit({
101+
limiter,
102+
key,
103+
error: (result) => new ORPCError('RATE_LIMITED', { data: { reset: result.reset } }),
104+
})
105+
```
106+
107+
:::
108+
96109
:::tip[Conditional Limiter]
97110
You can choose different limiters dynamically based on the request context:
98111

‎apps/content/docs/openapi/handler.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ const handler = new OpenAPIHandler(router, {
9494

9595
### Interceptors
9696

97-
These interceptors run only for matched requests, after routing and before error handling (but can't use `ORPCError` for [typesafe errors](/docs/error-handling#orpcerror-compatibility)). Use them when you need access to the matched procedure.
97+
These interceptors run only for matched requests, after routing and before error handling, and can use `ORPCError` for [typesafe errors](/docs/error-handling#orpcerror-compatibility). Use them when you need access to the matched procedure.
9898

9999
:::tip
100100
In most cases, `interceptors` are the best choice. They provide more context, are easier to work with, and run before error handling.

‎apps/content/docs/plugins/get-method-csrf-protection.mdx‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,16 @@ const handler = new RPCHandler(router, {
4343
The `handler` can be any supported oRPC handler, such as [RPCHandler](/docs/rpc/handler), [OpenAPIHandler](/docs/openapi/handler), or a custom one.
4444
:::
4545

46+
## Custom Error
47+
48+
By default the plugin throws `FORBIDDEN`. Use `error` to throw your own, which is [defined](/docs/error-handling#orpcerror-compatibility) when its `code` and `data` match an error the matched procedure declares. A custom code responds with `400` unless you map it in [`errorStatusMap`](/docs/rpc/handler#custom-error-response).
49+
50+
```ts
51+
new GetMethodCsrfProtectionHandlerPlugin({
52+
error: () => new ORPCError('CSRF_BLOCKED'),
53+
})
54+
```
55+
4656
## Cookie Requirements
4757

4858
Mark authentication cookies `SameSite=Lax` or `SameSite=Strict` explicitly. Do not rely on browser defaults: only Chrome treats unmarked cookies as `Lax`, while Firefox and Safari treat them like `SameSite=None`, and Chrome still sends fresh unmarked cookies on cross-site `POST` for [two minutes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Set-Cookie#lax).

‎apps/content/docs/plugins/request-limit.mdx‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,17 @@ The `handler` can be any supported oRPC handler, such as [RPCHandler](/docs/rpc/
3232
When used with [Request Compression](/docs/plugins/request-compression), `maxBodySize` applies to the **decompressed** payload size, not the compressed wire size.
3333
:::
3434

35+
## Custom Error
36+
37+
By default the plugin throws `PAYLOAD_TOO_LARGE`. Use `error` to throw your own, which is [defined](/docs/error-handling#orpcerror-compatibility) when its `code` and `data` match an error the matched procedure declares. A custom code responds with `400` unless you map it in [`errorStatusMap`](/docs/rpc/handler#custom-error-response).
38+
39+
```ts
40+
new RequestLimitHandlerPlugin({
41+
maxBodySize: 1024 * 1024,
42+
error: () => new ORPCError('TOO_BIG'),
43+
})
44+
```
45+
3546
## Peer Adapters
3647

3748
This plugin does not apply to peer-based adapters such as [WebSocket](/docs/adapters/websocket) and [Message Port](/docs/adapters/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](/docs/async-iterator-object) input). With Bun:

‎apps/content/docs/plugins/tmp-file-upload.mdx‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,15 @@ A multipart body splits across the first two limits, fields and part headers aga
105105

106106
With all three limits configured, the plugin subsumes the [Request Limit Plugin](/docs/plugins/request-limit). When the [Request Compression Plugin](/docs/plugins/request-compression) is present, limits apply to the decompressed payload rather than the compressed wire size.
107107

108+
To reject with your own error instead, use `error`. It is [defined](/docs/error-handling#orpcerror-compatibility) when its `code` and `data` match an error the matched procedure declares. A custom code responds with `400` unless you map it in [`errorStatusMap`](/docs/rpc/handler#custom-error-response).
109+
110+
```ts
111+
new TmpFileUploadHandlerPlugin({
112+
maxBodySize: { memory: 1024 * 1024, file: 100 * 1024 * 1024, stream: 1024 * 1024 * 1024 },
113+
error: () => new ORPCError('TOO_BIG'),
114+
})
115+
```
116+
108117
## Keeping Small Uploads in Memory
109118

110119
Uploads up to `spoolThreshold` stay in memory as plain `File`s, so small and empty files never cost a temporary file.

‎apps/content/docs/recipes/validation-customization.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ const handler = new RPCHandler(router, {
100100

101101
As explained in the [error handling guide](/docs/error-handling#orpcerror-compatibility), if you throw an `ORPCError` whose `code` and `data` match an error defined with `.errors`, oRPC treats it the same as `errors.[code]`.
102102

103-
This does not work in [interceptors](/docs/rpc/handler#interceptors). Use [client interceptors](/docs/rpc/handler#client-interceptors) or [middleware](/docs/middleware) applied before `.input` or `.output` instead.
103+
This works in [interceptors](/docs/rpc/handler#interceptors), [client interceptors](/docs/rpc/handler#client-interceptors), and [middleware](/docs/middleware) applied before `.input` or `.output`.
104104

105105
```ts twoslash
106106
import { RPCHandler } from '@orpc/server/fetch'

‎apps/content/docs/rpc/handler.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@ const handler = new RPCHandler(router, {
164164

165165
### Interceptors
166166

167-
These interceptors run only for matched requests, after routing and before error handling (but can't use `ORPCError` for [typesafe errors](/docs/error-handling#orpcerror-compatibility)). Use them when you need access to the matched procedure.
167+
These interceptors run only for matched requests, after routing and before error handling, and can use `ORPCError` for [typesafe errors](/docs/error-handling#orpcerror-compatibility). Use them when you need access to the matched procedure.
168168

169169
:::tip
170170
In most cases, `interceptors` are the best choice. They provide more context, are easier to work with, and run before error handling.

‎packages/node/src/tmp-file-upload-handler-plugin.test.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1649,6 +1649,53 @@ describe('tmpFileUploadHandlerPlugin', () => {
16491649
})
16501650
})
16511651

1652+
describe('custom error', () => {
1653+
const json = Buffer.from(JSON.stringify({ padding: 'x'.repeat(64) }))
1654+
const jsonHeaders = { 'content-type': 'application/json' }
1655+
1656+
it.each([
1657+
['a declared length', { ...jsonHeaders, 'content-length': String(json.length) }, json],
1658+
['a streamed body', jsonHeaders, json],
1659+
[
1660+
'a multipart field',
1661+
multipartHeaders,
1662+
createMultipartBody([
1663+
{ header: 'Content-Disposition: form-data; name="field"', content: 'x'.repeat(64) },
1664+
]).body,
1665+
],
1666+
])('throws the custom error when %s exceeds the limit', async (_, headers, body) => {
1667+
const error = vi.fn(() => new ORPCError('TOO_BIG'))
1668+
const plugin = new TmpFileUploadHandlerPlugin({
1669+
tmpDir,
1670+
maxBodySize: { memory: 10, file: Number.POSITIVE_INFINITY, stream: 10 },
1671+
error,
1672+
})
1673+
const interceptorOptions = {
1674+
context: {},
1675+
prefix: undefined,
1676+
request: {
1677+
method: 'POST',
1678+
url: '/upload',
1679+
headers,
1680+
resolveBody: async () => toStream(body),
1681+
} as any,
1682+
}
1683+
1684+
await plugin.init({}).routingInterceptors![0]!({
1685+
...interceptorOptions,
1686+
next: async (nextOptions) => {
1687+
await expect(nextOptions!.request.resolveBody()).rejects.toSatisfy(
1688+
(e) => e instanceof ORPCError && e.code === 'TOO_BIG',
1689+
)
1690+
1691+
return { matched: false }
1692+
},
1693+
})
1694+
1695+
expect(error).toHaveBeenCalledExactlyOnceWith(interceptorOptions)
1696+
})
1697+
})
1698+
16521699
describe('spool threshold', () => {
16531700
it('creates no tmp files for a flood of empty file parts before the procedure runs', async () => {
16541701
const { agent, captured } = createAgent({

‎packages/node/src/tmp-file-upload-handler-plugin.ts‎

Lines changed: 49 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { appendFile, mkdtemp, rm } from 'node:fs/promises'
55
import { tmpdir } from 'node:os'
66
import path from 'node:path'
77

8-
import type { Context } from '@orpc/server'
8+
import type { AnyORPCError, Context } from '@orpc/server'
99
import { ORPCError } from '@orpc/server'
1010
import type {
1111
StandardHandlerOptions,
@@ -105,6 +105,13 @@ export interface TmpFileUploadHandlerPluginOptions<T extends Context> {
105105
* @default 64 * 1024
106106
*/
107107
spoolThreshold?: number | undefined
108+
109+
/**
110+
* The error to throw when a body exceeds its `maxBodySize` limit.
111+
*
112+
* @default ORPCError('PAYLOAD_TOO_LARGE')
113+
*/
114+
error?: Value<AnyORPCError, [options: StandardHandlerRoutingInterceptorOptions<T>]> | undefined
108115
}
109116

110117
/**
@@ -176,6 +183,7 @@ export class TmpFileUploadHandlerPlugin<T extends Context> implements StandardHa
176183
undefined
177184
>
178185
private readonly spoolThreshold: number
186+
private readonly error: Exclude<TmpFileUploadHandlerPluginOptions<T>['error'], undefined>
179187

180188
constructor(options: TmpFileUploadHandlerPluginOptions<T> = {}) {
181189
this.tmpDir = options.tmpDir ?? tmpdir()
@@ -185,6 +193,7 @@ export class TmpFileUploadHandlerPlugin<T extends Context> implements StandardHa
185193
stream: Number.POSITIVE_INFINITY,
186194
}
187195
this.spoolThreshold = options.spoolThreshold ?? 64 * 1024
196+
this.error = options.error ?? (() => new ORPCError('PAYLOAD_TOO_LARGE'))
188197
}
189198

190199
init(options: StandardHandlerOptions<T>): StandardHandlerOptions<T> {
@@ -269,6 +278,7 @@ export class TmpFileUploadHandlerPlugin<T extends Context> implements StandardHa
269278
}
270279

271280
const maxBodySize = await value(this.maxBodySize, interceptorOptions)
281+
const createError = () => value(this.error, interceptorOptions)
272282

273283
/**
274284
* A form-data hint always means multipart here, even though it can also
@@ -277,21 +287,28 @@ export class TmpFileUploadHandlerPlugin<T extends Context> implements StandardHa
277287
* parser, which would fall back to urlencoded form data.
278288
*/
279289
if (resolvedHint === 'form-data') {
280-
return this.parseMultipartBody(request, tmpFiles, maxBodySize)
290+
return this.parseMultipartBody(request, tmpFiles, maxBodySize, createError)
281291
}
282292

283293
if (resolvedHint === 'file') {
284-
return this.parseFileBody(request, tmpFiles, maxBodySize)
294+
return this.parseFileBody(request, tmpFiles, maxBodySize, createError)
285295
}
286296

287297
if (resolvedHint === 'json' || resolvedHint === 'url-search-params') {
288-
return this.parseLimitedBody(request, hint, resolvedHint, maxBodySize.memory)
298+
return this.parseLimitedBody(request, hint, resolvedHint, createError, maxBodySize.memory)
289299
}
290300

291301
// Streams are consumed on the fly, but the decoder buffers each event whole, however fast the stream is read
292302
const eventLimit =
293303
resolvedHint === 'event-stream' ? maxBodySize.memory : Number.POSITIVE_INFINITY
294-
return this.parseLimitedBody(request, hint, resolvedHint, maxBodySize.stream, eventLimit)
304+
return this.parseLimitedBody(
305+
request,
306+
hint,
307+
resolvedHint,
308+
createError,
309+
maxBodySize.stream,
310+
eventLimit,
311+
)
295312
}
296313

297314
/**
@@ -302,14 +319,15 @@ export class TmpFileUploadHandlerPlugin<T extends Context> implements StandardHa
302319
request: StandardLazyRequest,
303320
hint: StandardBodyHint | undefined,
304321
resolvedHint: StandardBodyHint,
322+
createError: () => AnyORPCError,
305323
limit: number,
306324
eventLimit = Number.POSITIVE_INFINITY,
307325
): Promise<StandardBody> {
308326
if (limit === Number.POSITIVE_INFINITY && eventLimit === Number.POSITIVE_INFINITY) {
309327
return request.resolveBody(hint)
310328
}
311329

312-
assertContentLengthWithin(request.headers, limit)
330+
assertContentLengthWithin(request.headers, limit, createError)
313331

314332
const stream = await request.resolveBody('octet-stream')
315333

@@ -321,7 +339,7 @@ export class TmpFileUploadHandlerPlugin<T extends Context> implements StandardHa
321339
// An event can't outgrow a limit at or above the total one
322340
const fits = eventLimit < limit ? createEventSizeCheck(eventLimit) : undefined
323341

324-
const response = new Response(limitStream(stream, limit, fits), {
342+
const response = new Response(limitStream(stream, limit, createError, fits), {
325343
headers: toFetchHeaders(request.headers),
326344
})
327345

@@ -332,8 +350,9 @@ export class TmpFileUploadHandlerPlugin<T extends Context> implements StandardHa
332350
request: StandardLazyRequest,
333351
tmpFiles: RequestTmpFiles,
334352
maxBodySize: TmpFileUploadHandlerPluginMaxBodySize,
353+
createError: () => AnyORPCError,
335354
): Promise<StandardBody> {
336-
assertContentLengthWithin(request.headers, maxBodySize.file)
355+
assertContentLengthWithin(request.headers, maxBodySize.file, createError)
337356

338357
const stream = await request.resolveBody('octet-stream')
339358

@@ -351,8 +370,8 @@ export class TmpFileUploadHandlerPlugin<T extends Context> implements StandardHa
351370

352371
const upload = new UploadWriter(
353372
tmpFiles,
354-
new Budget(maxBodySize.memory),
355-
new Budget(maxBodySize.file),
373+
new Budget(maxBodySize.memory, createError),
374+
new Budget(maxBodySize.file, createError),
356375
this.spoolThreshold,
357376
)
358377

@@ -367,6 +386,7 @@ export class TmpFileUploadHandlerPlugin<T extends Context> implements StandardHa
367386
request: StandardLazyRequest,
368387
tmpFiles: RequestTmpFiles,
369388
maxBodySize: TmpFileUploadHandlerPluginMaxBodySize,
389+
createError: () => AnyORPCError,
370390
): Promise<StandardBody> {
371391
const contentType = flattenStandardHeader(request.headers['content-type'])
372392
const boundary =
@@ -384,7 +404,7 @@ export class TmpFileUploadHandlerPlugin<T extends Context> implements StandardHa
384404
*/
385405
const totalLimit = maxBodySize.memory + maxBodySize.file
386406

387-
assertContentLengthWithin(request.headers, totalLimit)
407+
assertContentLengthWithin(request.headers, totalLimit, createError)
388408

389409
const stream = await request.resolveBody('octet-stream')
390410

@@ -394,11 +414,13 @@ export class TmpFileUploadHandlerPlugin<T extends Context> implements StandardHa
394414
}
395415

396416
const limited =
397-
totalLimit === Number.POSITIVE_INFINITY ? stream : limitStream(stream, totalLimit)
417+
totalLimit === Number.POSITIVE_INFINITY
418+
? stream
419+
: limitStream(stream, totalLimit, createError)
398420

399421
const form = new FormData()
400-
const memory = new Budget(maxBodySize.memory)
401-
const file = new Budget(maxBodySize.file)
422+
const memory = new Budget(maxBodySize.memory, createError)
423+
const file = new Budget(maxBodySize.file, createError)
402424

403425
await parseMultipart(limited, boundary, (part) => {
404426
const name = part.name
@@ -442,11 +464,15 @@ export class TmpFileUploadHandlerPlugin<T extends Context> implements StandardHa
442464
* Rejects early when the declared length already exceeds the limit. The length
443465
* can lie, so the streaming enforcement stays either way.
444466
*/
445-
function assertContentLengthWithin(headers: StandardHeaders, limit: number): void {
467+
function assertContentLengthWithin(
468+
headers: StandardHeaders,
469+
limit: number,
470+
createError: () => AnyORPCError,
471+
): void {
446472
const contentLength = Number(flattenStandardHeader(headers['content-length']))
447473

448474
if (Number.isFinite(contentLength) && contentLength > limit) {
449-
throw new ORPCError('PAYLOAD_TOO_LARGE')
475+
throw createError()
450476
}
451477
}
452478

@@ -457,6 +483,7 @@ function assertContentLengthWithin(headers: StandardHeaders, limit: number): voi
457483
function limitStream(
458484
stream: ReadableStream<Uint8Array>,
459485
limit: number,
486+
createError: () => AnyORPCError,
460487
fits: (chunk: Uint8Array) => boolean = () => true,
461488
): ReadableStream<Uint8Array> {
462489
let total = 0
@@ -467,7 +494,7 @@ function limitStream(
467494
total += chunk.byteLength
468495

469496
if (total > limit || !fits(chunk)) {
470-
controller.error(new ORPCError('PAYLOAD_TOO_LARGE'))
497+
controller.error(createError())
471498
return
472499
}
473500

@@ -546,11 +573,14 @@ function indexOrEnd(bytes: Buffer, byte: number, from: number): number {
546573
class Budget {
547574
private used = 0
548575

549-
constructor(private readonly limit: number) {}
576+
constructor(
577+
private readonly limit: number,
578+
private readonly createError: () => AnyORPCError,
579+
) {}
550580

551581
charge(size: number): void {
552582
if (!this.tryCharge(size)) {
553-
throw new ORPCError('PAYLOAD_TOO_LARGE')
583+
throw this.createError()
554584
}
555585
}
556586

‎packages/ratelimit/src/middleware.test-d.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
import { os, type } from '@orpc/server'
1+
import { ORPCError, os, type } from '@orpc/server'
22

33
import { ratelimit } from './middleware'
4-
import type { RateLimiter } from './types'
4+
import type { RateLimiter, RateLimitResult } from './types'
55

66
describe('ratelimit', () => {
77
it('can infer context & input & meta types', () => {
@@ -38,6 +38,14 @@ describe('ratelimit', () => {
3838

3939
return 1
4040
},
41+
error: (result, { context }, input) => {
42+
expectTypeOf(result).toEqualTypeOf<RateLimitResult>()
43+
expectTypeOf(input.amount).toBeNumber()
44+
expectTypeOf(context.userId).toBeString()
45+
expectTypeOf(context.db).toBeString()
46+
47+
return new ORPCError('RATE_LIMITED')
48+
},
4149
}),
4250
)
4351
.handler(({ context, input }) => {

0 commit comments

Comments
 (0)