A developer creates a middleware.ts file in a Next.js application to handle authentication checks. The process involves defining unauthorized routes, checking for authentication cookies, configuring route matchers, and demonstrating the automatic redirection to a login page for unauthenticated users.
Length 5:21
Captions English (Generated), Spanish (Auto-translated), French (Auto-translated), Korean (Auto-translated), Portuguese (Auto-translated), Vietnamese (Auto-translated) #next.js #middleware #authentication #typescript #web development #cookies #routing #programming #javascript #coding
0:00 But we wanna implement authentication checks on our UI 0:04 to prevent unauthorized users from accessing pages if they're 0:08 not logged in. 0:10 Now, Next.js makes this super easy to do with 0:12 the help of middleware. 0:14 So middleware is going to allow us to run code before a request is 0:18 completed on the Next.js server. So we get access to the 0:22 incoming request, and we can modify the outgoing response, 0:25 just like 0:25 if we had middleware in our Nest.js application. 0:29 This is gonna be middleware on the actual Next.js server side. 0:33 Before we actually render any client components, we can run the request 0:36 through middleware, and this is the perfect opportunity to do an 0:40 authentication check. So in order to build middleware, 0:43 we simply have 0:44 to create a file in the root of the UI called 0:47 middleware.ts, and then Next.js will 0:51 automatically run this as middleware. 0:54 So we're gonna go export function middleware, 0:58 and this will automatically be a server function, so we don't have to 1:02 declare it as any. 1:04 And it gets, uh, passed in the next request to it 1:08 as a parameter. 1:10 So now inside of this middleware, I want to check to see if we have the 1:14 authentication cookie set on the current request. 1:18 So only the Next.js server would have access to the request to be able to set a 1:22 cookie on it, so we can check to see if that authentication cookie is 1:26 actually existing on it. 1:28 To do this, we'll have const auth equal to 1:31 request.cookies.get 1:34 authentication, and we want to access the .value if it 1:38 exists. 1:39 So this is gonna be the JWT cookie we know will be set by our server if we're 1:43 authorized. However, if we're not authenticated, 1:47 then I want to check to see firstly if we're not on the 1:51 login or sign up pages, or in other words, pages that we don't
The rest of the transcript is for members.
Sign in