The tutorial demonstrates how to implement server-side authentication in a Next.js application. It covers parsing JWT tokens from backend responses, setting secure HTTP-only cookies on the server, and updating a fetch utility to automatically include these cookies in requests to a Nest.js backend.
Length 12:18
Captions English (Generated), Spanish (Auto-translated), French (Auto-translated), Korean (Auto-translated), Portuguese (Auto-translated), Vietnamese (Auto-translated) #next.js #authentication #jwt #cookies #server-side #refactoring #typescript #backend #web-development #api
0:00 All right, so to get started in refactoring our app 0:03 to actually set 0:04 our authentication cookie on the Next.js server side, we'll of 0:08 course need to go back to our existing login server 0:11 action and update this so that we actually 0:15 check the raw response coming back here from our Nest.js 0:19 server where we know that there's going to be an 0:22 authentication cookie set if we're authenticated. 0:26 We want to parse that cookie and then set that value as a 0:30 cookie on our Next.js server so that all communication 0:34 between our Next.js UI and server will 0:37 have this authentication cookie set and then we can utilize 0:41 this authentication cookie later on when we actually wanna call our 0:45 Nest.js server. So let's go ahead and create a new 0:49 function that's gonna be responsible for actually setting the auth cookie. 0:53 So I'll call this setAuthCookie that takes in the 0:57 response here, type Response 1:00 and this will be a function. So we'll first check to see 1:03 if we actually have 1:04 the Set-Cookie header on the incoming response. 1:08 So I'll create a new set-cookieHeader 1:11 equal to response.headers.get 1:15 and we wanna pull off the Set-Cookie header 1:19 which the server is gonna set for our login route. 1:23 So if we actually do have a Set-Cookie header, let's go 1:26 ahead and now actually parse the JWT on 1:30 the Set-Cookie 1:32 header. To do this I'll create a new const called 1:35 token 1:36 and then we wanna call set-cookieHeader.split and 1:40 split on semicolon. So this Set-Cookie header is a string 1:44 that contains the JWT on it. We wanna split it on the 1:48 semicolon, access the first element in the array 1:52 and then split this again on the equals 1:56 sign and access the second element in the array. 1:59 So by doing this we can actually parse the Set-Cookie header and get the
The rest of the transcript is for members.
Sign in