0:00 Lecture, we wanna implement authentication for our 0:02 tRPC server. 0:04 As we know, back in our current tRPC implementation, 0:08 inside of 0:08 our posts router, 0:11 in the create post mutation, currently we're just passing in this stub 0:14 user 0:15 ID, which is taken directly from our database. 0:18 However, we don't wanna do this. Instead, we want to perform our 0:21 authentication with better auth, which is gonna validate our incoming 0:25 cookie just like it does for HTTP routes by default, thanks to our 0:29 global auth guard, but this does not apply to tRPC routes by 0:33 default. We need to do this ourself by implementing 0:36 our own custom 0:37 authentication check using Better Auth's API through some 0:40 middleware. So a middleware inside of our tRPC server 0:44 using 0:44 NestJS tRPC is gonna work just the same as we'd 0:48 expect in HTTP APIs. It's just gonna be a 0:52 function that we can execute before every procedure we 0:55 define inside of a router. 0:58 And this is a great place to do our authentication because we can check the 1:01 incoming cookie, which we know should be sent on the 1:05 incoming 1:05 HTTP request. Of course, tRPC is still over HTTP, so 1:09 we're just gonna look at these cookies being sent to our server, 1:14 pull the cookies off, and then use Better Auth to validate them, 1:16 and then finally 1:17 store the user on the incoming request object so that we can get 1:21 access to it. 1:23 And for this, we're gonna use tRPC context, which 1:26 is essentially just 1:27 some shared state that we can persist throughout the 1:30 lifetime of 1:31 a tRPC procedure. So let's go ahead and see how we can implement 1:35 authentication using this middleware and context from NestJS 1:38 tRPC. Okay, so to do this, let's go ahead and inside of our 1:42 auth directory, let's go ahead and create some 1:45 auth-trpc.middleware.ts 1:50 file. And so this will just be another
The rest of the transcript is for members.
Sign in