0:00 So in this lecture, let's go ahead and create some Next.js middleware, 0:04 which essentially is code that gets executed 0:07 before each and every request that hits our Next.js UI. 0:12 And so in this place, we're gonna put an authentication check to 0:15 see 0:16 if we actually have the 0:18 Better Auth session cookie set, which we know is only gonna be 0:22 set when we are actually authenticated. 0:24 And if we haven't, we'll let the request proceed. 0:27 Otherwise, we'll redirect the user back to the login 0:30 page. 0:32 To do this, let's head back into the web directory. 0:35 In Next.js middleware, we simply have to create a special file 0:39 called 0:39 middleware.ts inside of the root of the web directory. 0:44 And so in here, we'll go ahead and export default function 0:48 called middleware, and this gets passed in the request of 0:51 type NextRequest from next/server. 0:54 Now, the first thing I wanna do is check to see if we're on public routes, 0:57 because 0:58 we don't want this check to run on, for example, our login or 1:02 sign-up pages. We know that these are public routes, and we might have 1:06 other pages in the app eventually that we wanna expose to the public 1:10 without having the session cookie. 1:13 So let's create a dedicated array for this called publicRoutes and 1:17 put the /login 1:19 and the /signup route in here. 1:24 And the first thing we'll do is check to see the path 1:26 that we're trying to 1:27 navigate to. And to do this, we can destructure the 1:31 path name from 1:33 request.nextUrl. 1:40 And then we can check to see if publicRoutes array 1:44 includes the path name. 1:47 And so this will include the actual path we're trying to go to. 1:50 Well, if that's the case, we know this is a public route, so we can just 1:54 allow the request to proceed. And to do this, we call
The rest of the transcript is for members.
Sign in