Middlewares
You are able to add middleware(s) to a whole router with the middleware() method. The middleware(s) will wrap the invocation of the procedure and must pass through its return value.
Authorization
In the example below any call to admin.* will ensure that the user is an "admin" before executing any query or mutation.
ts
ts
See Error Handling to learn more about the TRPCError thrown in the above example.
Logging
In the example below timings for queries are logged automatically.
ts
ts
Context Swapping
A middleware can replace the router's context, and downstream procedures will receive the new context value:
ts
ts
createProtectedRouter()-helper
This helper can be used anywhere in your app tree to enforce downstream procedures to be authorized.
server/createRouter.tstsx
server/createRouter.tstsx
Raw input
A middleware can access the raw input that will be passed to a procedure. This can be used for authentication / other preprocessing in the middleware that requires access to the procedure input, and can be especially useful when used in conjunction with Context Swapping.
The rawInput passed to a middleware has not yet been validated by a procedure's input schema / validator, so be careful when using it! Because of this, rawInput has type unknown. For more info see #1059.
ts
ts