Next Auth - JWT & Session Callback & How to Update User Session

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's up YouTube today we are going to go over to asynchronous callbacks inside of next auth and that is going to be the JWT callback and the session callback this will allow us to update the Json web token sweet access CERN custom properties we want inside of the session object using the use session hook we're also going to go over the update method which will allow us to update certain properties inside of our object so before we get started if you can hit that like button and also subscribe for more content it would be greatly appreciated other than that let's get to coding so before we get started if you do not know how to use the credentials provider or not comfortable with it I highly recommend checking out my latest video where I go over step by step on how to use and set up properly the credentials provider because that is the provider I'm using in this tutorial I'm not using the Google or GitHub provider just the credentials provider and what we're going to do in this video is we are going to go over asynchronous callbacks so if we go inside of the docs these are functions that are used to control what happens when an action is performed we are going to go over the session function and the JWT function this will allow us to update the Json web token and we're also going to be able to update the session inside of our client so before we get started let's go over quickly the two ways that we can retrieve the session object inside of our application so if we go to our text editor we can go inside of This Server page that created and inside of this page I am fetching the session object server side so you can fetch a server side or you can fetch a client side fetching a server side you must use the get server session and import it at the top as so and this is from next auth then we have to initialize the git server session and we are passing through a parameter which is the auth options and this is the function that is inside of the catch-all route that is defining all of the options then you could console log the session and then you should be able to see all of this session parameters that we could get like the name email and image then we can use the use session hook which is a client-side way to fetch the session and what you have to do there is you have to create a provider and I usually create it inside of a context directory and this provider must use the use client directive at the top we have to import the session Provider from next Dash auth forward slash react then we must pass in the children and session and then we wrap all of the children inside of a session provider while passing in the session as a prop this means after we do this in the provider file we must go to our root layout and then we have to wrap the whole application or the children with the provider so we import at the top and then wrap the body with the provider this allows us to use the use session Hook from next Dash auth forward slash react and it has to be a used client page as well and then we can initialize the use session by calling it data so const data and we usually rename it to session and then you could also pass in a few other parameters like status and update which we'll go over later and this is going to equal the use session hook and I console logged it here thank you session hook session object and then we are just console logging the session so let's go to our localhost 3000 that is a quick overview of the two ways to retrieve the session so I'm going to log in with an account I re-registered and we are going to log in it's going to push us to this dashboard page and it's just showing my name if we inspect the page go to the console open up the object and inside the object we have a user object with an email image and name so maybe sometimes when you're doing an application this isn't enough information that you want to display to the user you might want to display somebody's address you might want to display somebody's phone number you could display their City you could display whatever you want you can actually add stuff to the session object and the only way you can do that is with the asynchronous Callback functions so before we go in to deaf about the Callback functions I have wrote a little few things so you could understand it better like I said we are using the credentials provider and inside of the credentials provider you always use the authorize function so let me just go back to the page go to the catch all route and if you look right underneath the providers where we Define the credentials provider we have an asynchronous authorized function which is a callback function and it is specific only to the credentials provider so what the authorized function does is what it says it authorizes the login so when I try to log into my application this is where all the logic is for when somebody logs in to make sure they are authorized to log in so that's the first function that's called off when somebody signs in after this function is called if you have marked your provider to use this JWT as the session then the JWT callback function will be called and then right after the jgw Callback function is called the session callback is called right after that so this is the order of how the callbacks are called and this isn't a very important step because that is going to help you understand on how to use these callback functions and how you could utilize it to your benefit so the very first thing I want to show you is how you can add a property or parameter to that session object so I want to add the address I want to show that we can display their address as well so we have to go to our register page where we register an account and this is just a form with a bunch of inputs and labels and inside the form we make them fill out their name email and password but we also want them to fill out an address so what I'm going to do here is I am going to just copy a div down with all the inputs and labels change the name the address change all of this address and then what we're going to do here is we'll change this address as well this is going to be data.address and the reason why is because the state that I defined up here in the U state is the data object with a bunch of properties and now we need to pass the address and as well and this is going to be initial value of empty string so now we have an input that is fully functional working for the address and if the state we are updating as well as they type because we have an on change here as well so when we scroll back up when we hit that submit on the form this register user function is called and is fetching to our backend API forward slash register route so we need to do here is we need to go to this backend route because we are just passing the data which is all the name email address and password so we're going to go to the backend register route and now we are receiving the body from a weight request.json and then I want to destructure it with name email address and password and this is going to be the body.data I usually like console logging when we're passing information to our backend API so we're at it there as well we're going to add a part of the check as well so if there's no address filled out on the input we're going to throw an error and then we have to I'm using Prisma as the orm and we want to pass that to our backend as well so it'll be the address just like that and then when you do this and you add a new field you must go to your schema.prism and make sure it's updated in your user model so I already have address here as an optional string you could do it as a required string doesn't matter and then when you make a change to your Prisma schema file make sure you run npx Prisma generate obviously shut off your development server before doing this and then you can restart your development server but since I already have it here we don't have to do that so let's go back to the register route so we are now registering a user with these four different properties to the back end so it's not going to update in next auth in the authorized function inside of that session object but we are able to send it to the backend now and we re and we're going to be able to get that address as well let's test it out to make sure our register function is working completely so to do that we are going to go to our Locos 3000 go to the dashboard like this if you go to click the register button and then as you can see register for account we could put Brett any email you want we could just say one three four one two three main street password one two three four five and then we can click register so if this is successful it pushes us to the login page I could check the console and as you can see we are getting all of the payload sent to the back end and then we can also make sure we had a 200 status and you could also check the database so we could just go to mongodb.com real quick sign in and like I said if you're not if you're not following the video I did prior to this or have your credentials provider set up this is going to be really for new so I definitely recommend like I said watching the videos on my channel in the past so we are going to go to the next auth practice video where I keep all the collection and I should have a user called Brett one two one three four at gmail right here and as you can see everything was successful so our register endpoint is actually working how it should now that we go back into our catch all route as you can see our authorized function is completely um filled out and done with all the logic needed and what we are doing is we are returning the user so right below this credentials provider outside of the providers we need to uh Define callbacks and like I said those are asynchronous callbacks that allow us to do certain actions when a certain event happens so we're going to have the callbacks and this is going to be an object and like I said we are using two callbacks we're using this session and the JWT the JWT gets triggered before the session so I always like putting that first so we're going to say async JWT and this is going to take in the token and the user and the session and if you do look at the docs you could see exactly what this specific callback function takes in so what we are going to do here is inside of the JWT I like to console log real quick what we are getting back and we could console log the token user and session and then what we're going to do here is we are just going to close this function and then we can put a comma now let's define the session function so it's going to be an async session and this is going to take in the session the token and the user so like I showed in that specific uh diagram that I created about five minutes ago the authorized credentials is going to get called it's going to return a user and then it is going to call this JWT function and then the token is going to pass from this JWT down to the session function and then the session allows us this function allows us to use it on the actual application so what I'm going to do here is I'm going to console log this to let me just close this first and let's console log the session callback with the session token and user and then we can just return the token on the first one because as we're returning and then return the session on the session function as well so now I'm going to log in with the account I just registered with so let's go back and I need a comma after the secret and I actually need to close the Callback so right there at the comma perfect all right so now I'm going to sign in with that account which is brett134 gmail.com and then we're gonna do one two three four five it's the password enter so now I'm on the dashboard I successfully logged in and I've console logged the JWT and the session function so we're going to check it out in the console and I'm going to explain exactly what's going on okay so the authorized function called a return the user and as you can see in the JWT callback we are getting a token and the token is showing the name the email the picture and an ID and then we are returning a user so the JWT callback function only Returns the user on sign in it doesn't return it every time the page reloads only when you sign in so as you can see here we are getting the user with the ID the name the email the address the hash password the email verified and the image so we want this address and you want the ID maybe inside of the session so we have to pass it from the JWT function to the session function and then if we scroll down again the JWT callback calls again and it passes all the information from the user to the token so as you can see now we have all of the information inside of the token except for the ones that we haven't defined yet which is the address and the ID so as you see address and ID are inside this token but they are inside of this user so we can move from the user to the token the user is undefined because it only is defined when you sign in and then the session callback gets called so as you can see the order JWT then session in the session it shows the session so when you console log a session it's the name email and image and then the token is so far the same token that got passed in so like I said we need to update the token in the JWT so the session can have the same token information as well because that session is going to allow us to use it on the client so to do that we are going to work inside of the JWT token this is where most of your logic and coding is going to be done so inside of the JWT token we are going to say if there's a user so that means on sign in there's going to be a user so on sign in we want to return and what we want to do is we want to put all the information inside of that token because that token is getting passed to this asynchronous function here so we're going to spread through all of the token data that we had that I just showed you and then we are going to get the ID and it's going to be from user.id so now the token.id is going to be the user.id so if we go back and look at it you see the user here it's only called we're getting the ID from here and we are placing it in the token here we also want to place that address as well so we're going to do the address and we're getting it from the user.address and this is storing it inside of the token because we are returning the token as you see here so other than that it looks like this function is completely done and we can retest Theory and if it works that means this JWT call pack the second time it's called with the user that's undefined should have the ID and the address in it so I'm going to do I'm going to go back to my localhost 3000 sign out go back we're going to log in with the same information right one three four password one two three four five we're gonna sign in okay when we sign in we're gonna get the consoles again and we're gonna get a user since we just signed in so we are going to scroll down below and we're started which is right here so we get the token and we get where is it hmm here it is right here okay so the JWT callback is called we get the token which we consulate here we get the user which we console logged again and now we are passing the user ID and the user address into the token so now we should have ID and address inside of the JWT callback token which as you can see right here we have a token inside of the JWT callback and we have the ID and address as well so that means this token now can be passed into the session which it does by default and if we go to the session we also have the ID and address and this ID is the mongodb ID and that's how we could hook up different posts to a specific user and it's very useful passing the ID to the session so now we have this token and now we can actually pass this information from the token into the session but we have to do a few things inside the session before we could actually access that onto our client so now that we successfully passed information into our token with this logic here which I'll just write a comment real quick pass and user ID and address to token so that's what this does here and then we return it then we get the token here and then what we need to do here is we need to return the session spread so everything in the session and if you want to look uh whatever it is the session is called right here which is the name email and image so the name email and image and then we're doing a comma and then we need to define the user because it's going to be inside the user object we are going to spread out throughout the session.user and then we are going to pass the ID which is the token.id and then we're going to pass them the address which is the token dot address and then we could just close this with a semicolon here and then what I can put Above This return is a comment saying pass in user ID and address to the session perfect so now we should be able to access the ID and address inside of the console as long as we're using the use session hook let me stop the server run the server again open up locals 3000 and then we're going to check the console to make sure we have the address and ID and if we do that means we successfully added a custom property to our session object so we're going to log in same email so after we log in we could check the console and see if we have those properties so I'm going to open it bigger Moment of Truth and as you can see instead of just the name image and email we get the address and ID as well and now that means we can display the address on the dashboard so now we successfully have integrated different properties into the session object this is how you do it by using the power of the session asynchronous function and also the JWT asynchronous function so the next thing I want to go over that is very powerful too if you look inside of the docs we will go to the client API folder and if you scroll down inside of the use session hook we can Expose and update method this allows us to update this session like say if we want to change my name from Brett to Mike we can do that by using the update method and we have to use these update method inside of this session and JWT asynchronous function to use the update method inside of these callback functions we need to pass in the trigger so trigger is another property we could pass into the JWT and then you could also pass trigger into session but we aren't going to do that because we're using the JWT as the session so what we are going to do is we have to have another if statement like this so right above that we could say if trigger equals update that means we are using the update method we and then we're also going to change the name so we're going to say if the session dot name is different we are going to run this block of code and what we are going to do here is we are just going to change the token dot name to the session.name so we haven't been able to change the session.name yet so if you run this code now the name is going to be the same name because you haven't changed it so what we need to do is inside of the dashboard right below where we say hi and whatever the session user's name is we can actually have a label and this label could say update name and then we can have it input so whenever we type in this input that is going to be our new name so we're going to say type equals text we could have a placeholder which is going to be enter new name and then we need some state so we already have the U State imported at the top and as you can see here I already have it initialized as the new name and set new name so the value is going to be a new name and you can name these State whatever you want I'm just naming it new name and then the on change is going to be an anonymous function and this is going to set the new name to the E dot Target dot value so whatever they type and then the only thing that won't work is if you try to wrap this in a form you cannot wrap this in a form I don't know why it doesn't work but it just doesn't so right below this I'm going to have a button and if you do look at the docs they do use a button as well so in the button I am just going to add a class name real quick and some other code that I have and I'm just going to say update that's going to be the name of the button that's what it's going to say and we are going to have an on click property on here as well so let's have another click and this on click is going to be anonymous function and it is going to call the update method like this and where we're getting an update method is from this use session hook as you see here I have it passed in as update and you could also do status is totally different has nothing to do with this um status has three different forms it's like authenticated not authenticated and something else but we are just using the update method that we get from the use session hook and what we're going to do is we are going to pass in an object because we want to change the name so we're going to change the name to the new name just like that so now we could type in the input and we should be able to change the session name to a new name of whatever we typed in and then what we do here is since we aren't done with the backend code the new session name is going to equal the new token.name that means that the token dot name is going to be returned as the token and it's going to pass in here the session as the new name and that means we need to update this as well so what we're going to say is name is going to equal whatever the token dot name is and that token.name is obviously going to be passed from the JWT call pack so let's do that and then I'm going to show you guys how to push this new name change to your mongodb database so let's test it out real quick to make sure so let's go to our locals 3000 as you can see we have update name enter new name and then we click update when we enter the new name this name should change instantaneous pretty much so like I said we can change it to Mike update it now says hi Mike we console log it we look at the object and the new name is Mike but if you don't update the database that you have if you sign out so for example I sign out try to log back in so let me log back in with the same email and then one two three three four five it's going to say Brett so hi Brett so it we need to update the database if we change the name so to do that inside of the JWT callback function we can update the database by using a prism method so what we could do is right below this logic here I'm just going to put a comment saying update the user and the database spread it out a little bit and then what we're going to say here is we're going to say cons new user you can name whatever you want it's going to equal a weight and then we are going to update the user by using the update method of prism and then we are going to find the ID which is the token ID which is technically the mongodb ID that we got from earlier so that is a unique identifier that we can use and then what we can do is we can update the data and we're going to update the name which is going to be the token dot name so if the token.name changes it's going to be the token.name if it doesn't change then it's just going to be the same name so that's why we're doing it exactly like that and then let's close this whole new user function and then right below that we can actually console.log the new user so this is going to pop up in our console here and then when we console log this this should be the new name which I'll type as mic so now we go back to our localhost 3000 we can refresh the page we get Brett so now we type mic update we get mic so now let's check our log real quick let's make this bigger and we are looking for the new user because that's what we named it and as you can see the new user is here and we get the name as mic and all the other information stays the same so let's check the database to see if Mike got updated to our user as well so if we refresh this page check out our entry inside of our collection and as you can see right here the new name is Mike and the email and address and hash password are still the same so you can update any property you want inside of your session object I just happen to do the name for this example and that is exactly how you use the update method that is how you use the asynchronous JWT function callback and the session function callback while using the credentials provider if you are using the Google provider or any other provider the method will be a little different so I only recommend using the credentials provider if you're following this tutorial and I do want to show you if I do sign out go back and log in it's going to say mic so we're going to log in same account and it says mic so that is how you successfully use the asynchronous callbacks with the update method if you do have any questions I know it is a hard subject to wrap your brain around leave a comment below or join my Discord room where I'll be able to answer you quicker but other than that if you've gained any value of this or learned a lot please hit that like button and also subscribe for more content just like this
Info
Channel: Brett Westwood - Software Engineer
Views: 29,061
Rating: undefined out of 5
Keywords: next auth, next js, next js tutorial, next auth jwt, next auth credentials, next auth prisma, next auth update session, next auth update session data, next auth update session user, next auth async callbacks, next auth callbacks, how to use the next auth callbacks, next auth jwt refresh token, next auth jwt callback, next auth session callback, next auth jwt example, next auth jwt authentication, next auth update method, next auth update token, next auth tutorial
Id: bkUmN9TH_hQ
Channel Id: undefined
Length: 31min 34sec (1894 seconds)
Published: Thu Jul 13 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.