A developer implements a logout server action in a Next.js application, updates authentication checks using cookie values, and configures middleware. The tutorial then demonstrates programmatic routing using the useRouter hook for both mobile and desktop menus, ensuring smooth navigation without full page reloads.
Length 14:28
Captions English (Generated), Spanish (Auto-translated), French (Auto-translated), Korean (Auto-translated), Portuguese (Auto-translated), Vietnamese (Auto-translated) #next.js #web development #authentication #server actions #coding #middleware #routing #react #javascript #typescript
0:01 All right, so in this lecture, we want to actually implement our 0:04 logout capability, so when we click Logout, we are actually 0:08 logged out. So that's gonna involve actually clearing 0:11 the 0:11 authentication cookie we have set on the Next.js backend. 0:17 So let's create a new server action that's going to clear this cookie out 0:21 for us. I'll go into auth and create a new 0:25 logout.ts file, 0:28 and we'll export this server action, 0:32 which is gonna be an async function called logout. 0:37 And we're going to call cookies from next headers 0:41 and then the 0:42 delete function on it and specify the 0:46 authentication cookie name. Now, we've used this cookie 0:50 name twice now as a string literal 0:53 in both of these server actions. 0:55 So I'm gonna create a new 0:57 authCookie.ts, 1:03 and this will be a const we'll export called 1:07 authenticationCookie, 1:11 and we'll just call this authentication string literal. 1:14 And now we can reference this constant in both our 1:17 authenticated server action 1:20 and the logout server action, so we're always going to be 1:23 setting and deleting the exact same 1:27 cookie. 1:29 So now that we're deleting the authentication cookie in this way, we 1:33 need to go back to our authenticated server 1:36 action where we are currently checking to see if the 1:40 authentication cookie exists. That's determining the authentication 1:44 status. However, when we clear the cookie in this way 1:48 after it's already been set using delete, that's simply 1:52 going to set the value on the existing cookie. 1:55 It's gonna override it to an empty string. 1:57 So we need to update our authenticated check here to check 2:01 for the .value string on this actual 2:05 cookie object. If this exists, then we know we're authenticated 2:09 opposed to just having the object altogether, which was fine 2:13 originally. 2:16 Additionally, we can utilize this new 2:18 authenticationCookie constant in a couple of other
The rest of the transcript is for members.
Sign in