T
tRPC

Middleware or request lifecycle hook to run after procedure?

Middleware or request lifecycle hook to run after procedure?

Mminty11/16/2023
Hi, I am using trpc context to create a database client for an incoming request. My understanding is this runs for every request, which is what I want. I want to be able to systematically close the databaase client at the end of any TRPC request. Is there any way of doing this? Perhaps with a middleware or request lifecycle hook? I couldn't find any documentation on it. This is the structure I want:
1. Request start
2. Context is created --> DB open
3. Procedure runs
4. DB is closed
1. Request start
2. Context is created --> DB open
3. Procedure runs
4. DB is closed
Thank you!
Solution:
is this sort of what you mean? ``` const withDb = middleware((opts) => { const db = getServerlessDBInstance();...
Jump to solution
Nnlucas11/16/2023
Yep just await next() into a variable, do your work, and then return the variable But generally with DBs you want to have a persistent pool, opening and closing connections is expensive, so maintaining a pool instance means there are always some open connections available
Mminty11/16/2023
I am using Neon (neon.tech) as my DB provider and they explicitly say to close it at the end of every request:
The Pool and Client objects must be connected, used, and closed within a single request handler. Don't create the objects outside a request handler; don't create them in one handler and try to reuse them in another; and to avoid exhausting available connections, don't forget to close them.
The Pool and Client objects must be connected, used, and closed within a single request handler. Don't create the objects outside a request handler; don't create them in one handler and try to reuse them in another; and to avoid exhausting available connections, don't forget to close them.
from here: https://neon.tech/docs/serverless/serverless-driver Can you explain what you mean why the awaiting the next() variable? I would like the procedure to have access to the ctx.db, but not have to remember to close it Oh I think I see what you mean. Like the middleware would be:
openDB()

const result = await next()

closeDB()

return result
openDB()

const result = await next()

closeDB()

return result
is that what you mean?
Nnlucas11/16/2023
Fair enough then! Obviously their advice takes precedence 🙂 Yep! Middlewares are flexible 🙂
Mminty11/16/2023
got it, thank you! I will try that out
Nnlucas11/16/2023
You can add the DB in to the ctx by passing it to next() as well
Mminty11/16/2023
ahh perfect ok
Nnlucas11/16/2023
it will be merged, no pain needed from you
Solution
Mminty11/16/2023
is this sort of what you mean?
const withDb = middleware((opts) => {
const db = getServerlessDBInstance();

const result = opts.next({ ctx: { db } });

return result;
});
const withDb = middleware((opts) => {
const db = getServerlessDBInstance();

const result = opts.next({ ctx: { db } });

return result;
});
Mminty11/16/2023
(obviously I will add the db.end() as well)
Nnlucas11/16/2023
Exactly

Looking for more? Join the community!

T
tRPC

Middleware or request lifecycle hook to run after procedure?

Join Server
Recommended Posts
Use RxJS Observable for subscription procedureOn the server, I have an RxJS Observable that I'd like to use for one of my subscription procedures.Individual mutation requests errorHello, quick question regarding the error handling for tRPC So I'm creating kind of a chatroom wherTRPCClientError: fetch failed, using Node 18 in DockerI have both my app and my tRPC server running in Docker via the following docker-compose config: ("nNeed help how to send headers in trpcproject is setup with express on 2 parts,cleint and server i have this pice of cod in client side ``"fetch failed" when buildingHi, we are running into an issue where building our production next app causes "fetch failed" errorsanyone has an example of SSR with React query working without Next js?Can't find a working exampleLooking for an up to date boilerplate for tRPC & Fastify.Looking for an up to date boilerplate for tRPC & Fastify.Can You Provide Guidance on Implementing RBAC and Share GitHub Examples?I am currently exploring the implementation of Role-Based Access Control (RBAC) and am seeking your `useQuery` not working?is it just me or does `useQuery` not work in my next js components? i try to call it and it says cliServer Component Call to TRPC on express backendI have following structure: - Nextjs App folder with both client components and server components - Can set cookie with trpc?I tried to create a full authentication system in trpc using jwt and refresh token I find that is notrying to understand how this worksso i'm looking at the t3 template that was made for me, and there seems to be a `trpc` folder that ccan't call nested routethis is the top level router: ```ts const appRouter = router({ hello: procedure.query(() => 'heltrpc authDid someone create a full auth system in trpc (with next js trpc react query prisma,jwt token, refreDifference between createTRPCNextAppDirServer, createTRPCNext and createTRPCProxyClient?Hey everyone. I struggle to understand the difference between these 3 TRPC functions when it come tWhat is the mutation error type?In the provider I want to set onError for all mutations: ```ts new QueryClient({ defauMerging two clients into oneI have two clients. One for react-query for client components and one for server components. I wannaIs it possible to only use WebSockets when necessary, otherwise use httpbatch or http?I have an application, and on certain pages I need live data. Is there a way to only have tRPC open Zod transform typesI have a zod type for our backend requirements that looks like this: ```javascript const ZCustomTypeuseQuery in App Router?I have a client component that I want to use useQuery in like in pages router, but only `query` is a