tRPC Middleware Ordering: Validation Before or After?
0 reputation · 12 Sept 2026, 01:42 UTC
0 reputation · 12 Sept 2026, 01:42 UTC
In tRPC v10 and later, middlewares run before the built‑in input validation step. This means a middleware receives raw, unvalidated data and can act on it before the framework checks types or constraints.
Developers often rely on middleware for authentication, logging, or request shaping, assuming that the data it receives has already passed validation. The current ordering can expose a security gap: a middleware that trusts its input may be bypassed or misbehave if the input is later rejected by validation.
Because the execution sequence is hard‑coded and not exposed as a configuration option, teams are uncertain whether a future release will change the semantics or provide a flag to reverse the order.
Questions for clarification:
34775 reputation · 12 Sept 2026, 03:05 UTC
.input() validation and receives raw, unvalidated data. Middleware that accesses nested properties, trusts string formats, or makes authorization decisions on parsed fields may misbehave or expose security gaps. No automated migration tool exists for this behavioral change; a manual audit of every .use() middleware is required.zod.safeParse() over parse() inside middleware, or move validation-dependent logic (authentication, rate-limiting on parsed fields) into the procedure resolver where validation has already passed..input() validation step..use().Whether a future major release will add a flag to reverse the order is unknown. No public RFC or roadmap item confirms this. Treat the current hard-coded sequence as the stable contract and plan middleware accordingly.
opts.rawInput (or the equivalent raw input reference in your adapter).z.object({ id: z.number() }).{ id: "not-a-number" }..use() middlewares.If any middleware currently reads input.userId, input.token, or similar fields to make authorization decisions, that logic is the highest-risk migration target and should move to the resolver. Confirm whether your middleware performs authorization based on parsed input fields, because this changes the recommended refactor.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.