lukas
lukas2y ago

It is possible to define a middleware for all routes?

Instead of creating a public/protected procedure and using it for every procedure I was wondering if TRPC has any option to define it in the route definition itself:
7 Replies
Alex / KATT 🐱
Define Procedures | tRPC
Procedures in tRPC is a very flexible primitive to create backend functions; they use a builder patter which means you can create reusable base procedures for different parts fo your backend application.
lukas
lukasOP2y ago
thanks for the quick reply! yet I have to define it manually in every procedure definition. I was looking into something that I could define in a route level and automatically be applied to all procedures in that router and sub routes.
lukas
lukasOP2y ago
I am doing that already as shown below, but I was trying to do this in a route level so I wouldn't have to repeat it everytime again.
Nick
Nick2y ago
This was something I had to adapt to as well, but the reason I believe they did it this way was a good typescript experience. Middleware’s can change the Context type, and by adding middlewares to the base procedure any procedures which build on it automatically have the right type definition. What are you having to repeat though? What's the difference fundamentally between doing procedure.query(...) 10 times vs protectedProcedure.query(...) 10 times? You define them once in some central (or co-located to a router) location and build on them as many times as you want
Alex / KATT 🐱
what i experienced with v9 too - where we did it at a route level - is that i often wanted to opt out of the middlewares deep in a router somewhere i want to have "domain logic" in the same space so if i have a "post" router there might be some routes that are public like (read) and some that are protected like create/update
Nick
Nick2y ago
Makes a lot of sense, there’s a learning curb to it but lots of benefits
lukas
lukasOP2y ago
Yeah, that makes sense. I am replicating it again but in my case is because I am developing a multi tenancy app where I have multiple roles and I am developing a sub route for each Roles as trpc/next doesn't support multi trpc clients atm yet

Did you find this page helpful?