Next Auth - JWT & Session Callback & How to Update User Session
In this video, I go over how to use the asynchronous callbacks of the JWT function and session function. This will allow you to use the JSON Web Token for your session data.
Also, I go over the update method provided by the useSession Hook. This allows you to update the session object.
Private 1 on 1 Help 👇
calendly.com/dabrettwestwood/...
Join my FREE Discord to talk and network about web development! 👇
/ discord
Time Stamps
0:00 Intro
1:18 getServerSession and UseSession Overview
4:24 Explanation of how the callbacks work
5:49 Creating a custom property inside of Register Endpoint
10:47 Create the JWT and Session Callbacks
21:48 The Update() Method
27:52 Update the user in database
30:42 Outro
Пікірлер: 163
Finally I found a way to do this, I searched everywhere but couldn't find it. Thanks, awesome video.
man you're doing great job. Nextjs has no many tutorials out there that highlight things as you do. Highly appreciated!
@brettwestwooddeveloper
Жыл бұрын
Thank you!
This is my second tutorial from Brett, this was amazing thanks so much. You make wath seems very complicated and you simplify it for us. Thanks again
@brettwestwooddeveloper
Жыл бұрын
Thank you for the kind words! I am glad you are tuning in!
Thank you for being (seemingly) the only person anywhere to explain the callbacks in NextAuth. This was a huge help!
@brettwestwooddeveloper
10 ай бұрын
No worries! You are welcome!
this video is wonderfull sir , i have watched many a videos related to next auth and was struggling with it since 1 month but after seeing your 2 videos all my doubts came to an end , this is the best video on internet on next auth , thank you soo much sir
This is the best video on callbacks I have seen. Thank you for walking through it in such a systematic manner.
@brettwestwooddeveloper
2 ай бұрын
No problem! Appreciate the feedback!
Thank you so very much !! Your "The Ultimate Guide to Next Auth" video and this one are SUPER for beginners and probably the most thorough content on KZread on Next-Auth. May be, if you have time and energy, sometime in future, a nice relaxed discussion, or a nifty little series on JWT + cookies + session + authentication + authorization + database session etc especially in light of NextJS + NextAuth would be fantastic. I guess this is how we beginners are !! Greedy !! :-). Once more, MAGNIFICENT, FABULOUS. THANK YOU SO VERY MUCH !!!
@brettwestwooddeveloper
Жыл бұрын
Thank you for tuning in! I would be glad to make a video along those topics.
Thank you so much for doing such high quality content around nextauth callbacks!! Helped me so much.
@brettwestwooddeveloper
4 ай бұрын
No problem! Thank you for tuning into my channel!
Great video man. Just what i needed. Everything explained clearly and perfectly.
Much better than other tutorials, thank you very much !
You just earned a new follower bro. I have been struggling with session updates for a while but you just made it look so easy. Thanks ❤
@brettwestwooddeveloper
10 ай бұрын
Thank you so much for the follow!
This tutorial literally just saved my life
Honestly, this is the best video ever on this topic. I've been struggling with NextAuth - "in my opinion, the documentation is either bad or I'm just dumb" - but it was explained so well! Subscribed.
@brettwestwooddeveloper
11 ай бұрын
Thank you so much!
@st7171
10 ай бұрын
Yea Documentation isn't helping that much, but utubers are there for us 🥰
Thanks man ! it really helped a lot. No other tutorial regarding callback with mongo is out there. Would love to see more like these.😃
@brettwestwooddeveloper
10 ай бұрын
Appreciate it! Thanks for tuning in!
Perfect video, just what i looking for!
@brettwestwooddeveloper
10 ай бұрын
Awesome! Thanks for tuning in!
Best of the best video and teaching style. Thumbs up. You solved my issue. Best regards
@brettwestwooddeveloper
10 ай бұрын
Glad it helped!
Thank you, you just help me solve my problem on adding additional session.
@brettwestwooddeveloper
8 ай бұрын
Happy to help!
Thanks for your great content! You're doing a great job at explaining. keep going :)
@brettwestwooddeveloper
8 ай бұрын
Thank you! I will!
bravo couldn't navigate next-auth in the app directory without you
@brettwestwooddeveloper
11 ай бұрын
Thank you! Glad I could help you out there!
wish i could like this vid a hundred times.Thanks Brett🙌
@brettwestwooddeveloper
11 ай бұрын
Glad you liked it!
You actually cooked with this tutorial no other tutorial like this.
Great, I'm learning nextjs with these videos I already took a big step
@brettwestwooddeveloper
8 ай бұрын
Awesome! Thanks for the sub!
Dude, this earned you a subscribe, and i still didn't finish the video. Thanks!
@brettwestwooddeveloper
29 күн бұрын
Thank you so much for the sub! Really appreciate it!
Thanks. this video really helps me
@brettwestwooddeveloper
8 ай бұрын
No problem! Glad I could help you out
This video helped me a lot. I appreciate it
Great explanation, thank you!!!!
@brettwestwooddeveloper
7 ай бұрын
You're very welcome!
thanks . that's the thing iam looking for and i got it after 3 days of search
Thank you man! you've saved me today!
amazing video king. earned a subscriber👌👌
@brettwestwooddeveloper
6 ай бұрын
Thank you so much!
Well done video, I've learnt a lot from it.
@brettwestwooddeveloper
Жыл бұрын
Thank you!
Good job broh! Great content!
Its Really Helpful video for me
@brettwestwooddeveloper
8 ай бұрын
Awesome! Glad I could help you out!
thanks for the video , from argentina
nice job! tksss a lot!
@brettwestwooddeveloper
10 ай бұрын
No problem! Thanks for tuning in!
Thanks!
omg this video saving me
@brettwestwooddeveloper
6 ай бұрын
No problem Daniel! Glad I was able to help you out! Any suggestions for more content you would like to see?
Amazing video! I hope you create like a full admin dashboard tutorial using the credentials provider
The Complete T3 Stack Course would be game changing!
@fadlo1580
11 ай бұрын
strongly agree
Big help
legend
@brettwestwooddeveloper
4 ай бұрын
Thank you!
Your video helped me a lot. thank you In my program, I can retrieve sessions from ssr and csr, and update session information through update() in csr. Is there a way to update the session in ssr?
You are perfect
Thank you for explaining the callback functions it helped me in my project! Can you also make a video on "Remember Me" functionality with Next Auth?
@brettwestwooddeveloper
8 ай бұрын
Glad I could help you and I can look into it
Thanks bro for very helpful video. But I want return accessToken for middleware authentication, how can I achieve it?
Thanks for the great content! I really appreciate it. I have one question when updating the name field on line 72 in JWT callback function @29:24. I expected that the return block on line 64 would prevent the update from happening and would return token before even reaching the database. Do you know why that return didn't happen at all on line 64, but further processing happened on line 72? Thanks
@brettwestwooddeveloper
8 ай бұрын
Hey Vlad thanks for the sub! And honestly I have no clue why
how do you pass data from the login form to the signIn callback?
man, can u please teach me how to get the jwt token genereted by next in account parameter? mine is always undefined
Hello, I am developing the front-end of a project with Next.js, but the back-end of the project is in Django. I want to know if I can use NextAuth for authentication without causing any issues with the Django back-end? Also, could you advise me on whether I should store the token in a cookie or use NextAuth? Please guide me.
I have a question about managing the database using the update function. It works well if we want to update one value in the user model. However, if I want to change once a name, once an address, and another time a property in a completely different model, the update function will not work. For database management, isn't it better to create API endpoints that are called by fetch? The data would be retrieved using useSWR, updated using fetch (POST, PUT or DELETE), and only the user ID would be contained in the session object. Am I right?
@brettwestwooddeveloper
Жыл бұрын
yes you are right, I think the update function can only update the session data. If you want to update anything in the session data, like name, email etc. you can use update. If you want to update a completely different model then you won't use update and do as you stated.
Great ❤
@brettwestwooddeveloper
Жыл бұрын
Thank you!
Using NextAuth EmailProvider and trying to set a mergeLocalCartToServer: true flag on session during initial signin. Neither signIn nor JWT callbacks are triggered, only session. How can I set it only on initial signin? Any guidance is super appreciated.
@brettwestwooddeveloper
8 ай бұрын
I honestly have no clue
How create custom login with email and pass only?
i tried do the same, but when i tried to pass phone number on async jwt() passing like: phone: user.phone i got error like this: Property 'phone' does not exist on type 'User | AdapterUser'. Property 'telefone' does not exist on type 'User'.ts(2339) any i dont understande why cause i am confirmed get all data i need on user
this is super helpful, thanks a lot. how to fix typescript errors since it shows errors trying to accept my custom properties in the useSession() hook or getServerSession, ```Property 'type' does not exist on type '{ name?: string | null | undefined; email?: string | null | undefined; image?: string | null | undefined; }'.```
@brettwestwooddeveloper
4 ай бұрын
That error is due to the session object only having the properties of the name, email and image by default. Are you trying to add another value on the jwt token?
any extension you use in the console? i can't find it in the console
Hi, I have some doubts about using next-auth, what if i want to have an external api? I dont see a way of making the authorization for that external api routes using the jwt generated in the client-server in a simple wa ,maybe sending the user and checking if exist in the db in a middleware in the node external server but i dont think is a good practice, is there any way of generating the jwt on the external api and refresh it and keep using next auth? I ask this bc in the future I dont know if i will have a mobile app, and leave all api responsabilities to next.js doesnt seem to be that good
@brettwestwooddeveloper
Жыл бұрын
honestly that is a good question, and I don't know if they do. I know they are constantly working on new features and they are working on the new docs as well
Thank you
@brettwestwooddeveloper
11 ай бұрын
You are welcome!
this is a great video. you should have used typescript though!
@brettwestwooddeveloper
7 ай бұрын
Next time!
Great job, how to update adress and name ?
How do you console log so fast?
After initial login, I want to redirect the user to a form to fill out additional information, what would be the best way to implement that? By using a middleware that calls after the initial login or can I do that with the callback?
@brettwestwooddeveloper
11 ай бұрын
thanks for tuning in and the best way to redirect after a sign in would be to define it in the catch all route. This is going to be an option called pages. It would look something like this. pages: { signIn: "/dashboard" }, this will redirect every sign in to the dashboard page
hey, you have done for credentials provider right, can we do it for other providers like google and how?
@brettwestwooddeveloper
8 ай бұрын
I have tried the update function for Google and it did update in the database but whenever I logged in with the Google Provider, no matter what I did. It took the name and email from the Google Provider. So, I don't think the updater function works on the google Provider. I would assume the same with others. However, you can use the JWT and Session callbacks for all providers. Hope this answer was clear.
thanks for the tutorial. it was very helpful. however, I cannot make the getServerSession method to work. it returns only the out of the box properties. any pointers? thanks in advance
@brettwestwooddeveloper
5 ай бұрын
No problem. So, is it working client side when using useSession?
@leof240
5 ай бұрын
@@brettwestwooddeveloper yes. it's working perfectly client side but server side returns only the default properties, so for example, the role property that I set in the callback is not shown in the getServerSession
@leof240
5 ай бұрын
@@brettwestwooddeveloper actually I was able to make it work setting additional properties the javascript way and not the react way (with ...session, etc.)
I've got an error. Even though user is logged in session returns undefined, im using it in serverside component
@brettwestwooddeveloper
7 ай бұрын
ummmm, can you send me your code and I can review it. Message me in Discord group
If you refresh the page at 21:27 then the "id" and "address" properties will be gone from the "user" object. But they'll be added again if you click on a different browser tab and then return the the browser tab containing the app. Anyone know how to preserve those new properties on the session even after a page refresh? I've been struggling with this for a few days...
@user-ek7pw7ds6x
10 ай бұрын
Update: fixed it. It works perfectly with the SessionProvider you're using in this video. I was using `const session = await getServerSession()` to get the session that was passed to the SessionProvider wrapping my app which apparently is incorrect.
Okay but how will you update the session data from database. Let's say I have a property user_roule on User which is changed by admin. I would like to update the session data and see fi the role is changed.
@brettwestwooddeveloper
Жыл бұрын
depends on which ORM or database you are using. prisma.user.update, etc...
I am doing the nextAuth, but when I refresh the page, the session is lost. Can you show me how to fix it?
@brettwestwooddeveloper
8 ай бұрын
Can I see more of your code to help you out?
Very nice video bro😉. Which version of next are you using? have a problem with this error: async/await is not yet supported in Client Components, only Server Components. This error is often caused by accidentally adding `'use client'` to a module that was originally written for the server. I think it may be couse becouse you pass session as an prop in provider but you didn't use it. I check that I can't wrap server component by client side component. I will be very grateful for your answer
@brettwestwooddeveloper
8 ай бұрын
Yes I am using next.js 13 and the that error is specific to version 13 because client components can't have server functions inside of them. Is it letting you know which component the error is on?
@natanuczak2640
8 ай бұрын
@@brettwestwooddeveloper thank you for your respond. I have already resolved this error. I made a dumb mistake😉
ahh very nice if someone just change the token name and update this, then what happen? rather then using pure id name, jwt isn't better? so anyone can't see the user id? the user id is available on the client without encoding. am i wrong?
with the logic you created for updating the user session, is it safe? next auth docs state that the value should be validated, but im not entirely sure how to do that. i heard a user can change any session value if not
@dissatisfaction
7 ай бұрын
or is the "&& session?.name" in the trigger if statement the validation? does that check to make sure only the name can be updated?
Refresh tokens how
Great Video! The only question I have is Why do you need the session callback if the jwt strategy is used? Because isn't the jwt sent to the client itself as a cookie to manage state?
@brettwestwooddeveloper
Жыл бұрын
You need the session callback because the JWT callback only updates the JWT in the backend. You need to send the JWT to the session. You can't manage the session object without it.
@seanharricharan7602
Жыл бұрын
@@brettwestwooddeveloper understood, I had a feeling this was how it worked but wasn't 100% sure, Thank you!
Amazing! video. Is there no way to logout user on the server side? I've read the documentation and made a lot of research still no where to find that solution, please any solution or work around? I will really appreciate.
@brettwestwooddeveloper
Жыл бұрын
I don't think there is, you can create a button component this is client side and just import into your server side file.
@successoronyemaechi
Жыл бұрын
@@brettwestwooddeveloper Wow! Thanks, I will give it a trial.
I'm a bit confused about the order in which I should watch the authentication tutorials. Could you please provide an index of all the tutorials?
@brettwestwooddeveloper
Жыл бұрын
I would recommend watching the Credentials Provider video then this one.
@OnlyJavascript
Жыл бұрын
@@brettwestwooddeveloper thank you so much.
I have a dilema. Authentication is not really my strongest point, and I fail to see how can I solve the problem I have. I have an external API which gets called from the app, mostly for storing files and some other things... How can I use the token provided by the Next Auth to authenticate on that API. And how can I invalidate a token, if let's say the token gets stolen. I'm trying to understand how refresh tokens works, but I'm not really understanding anything. And yes, I need to use the username / password, not a third party service, since this is for a small company, where only thier employees needs acces to it. I used firebase until now, but I'm rewrinting it and they want to drop any external service dependecy.
@brettwestwooddeveloper
8 ай бұрын
Can't you check against the database and use the getServerSession provider which is server side code?
Hey Brett very useful video!💯 Also can you make video including accessToken and refreshToken for authorization
@brettwestwooddeveloper
Жыл бұрын
I can research it but I think its very similar to what I did in this tutorial
@WM-fz5si
Жыл бұрын
@@brettwestwooddeveloper Hey brett the data which we are accessing through session is also visible in network tab when we inspect. So it that safe?? Because I am passing accessToken in it for authorization? What is your view on it?
@brettwestwooddeveloper
Жыл бұрын
@@WM-fz5si you shouldn't pass anything secret into session. However, I think I have seen people pass that into session
@WM-fz5si
Жыл бұрын
@@brettwestwooddeveloper than which method will be best to get the accessToken??
do you have a github repo
How do I implement real-time user roles with credentials provider? I have set up my db's UserModel to accept a role Enum consisting of "user","mod" and "banned" but the issue is once the jwt token gets sent to the user even if I change the user's role server-side, they still hold on to their old role via the token. The only way that I've found out to work is to fetch the user from db every time they access the protected page but that's neither scalable nor practical in any way. Real-time role management is important in a lot of website types (forums, online games etc) and I have no idea how to do it (and auth js's documentation is not helping at all).
@brettwestwooddeveloper
2 ай бұрын
You should be passing the role from the JWT to the session object. It should be changing based on the new role if you do it like this.
@nasko235679
2 ай бұрын
@@brettwestwooddeveloper It's changing only when the user reauthenticates, not in real time.
@brettwestwooddeveloper
2 ай бұрын
@@nasko235679 Does it stay changed after they reauthenticate?
@nasko235679
2 ай бұрын
@@brettwestwooddeveloper Yes, the issue is that once the token is issued and the user has their role inprinted in it, you can't force them out so even if you decide to ban them (by simply changing their role to "banned") it won't reflect in their experience at all unless the token actually has an expiration mechanism (like make the token expire every 5 minutes and combine it with a refresher token so the user doesn't get logged out) however there's 0 documentation about that because..well because authjs documentation is utter s*!t.
@brettwestwooddeveloper
2 ай бұрын
@@nasko235679 ahh i see. Yes I have never implemented it like you are explaining. I would then just set the role to the user in the database and query it that way. Of course, this isn't ideal but will work
What extension advices you the code?:)
@user-of8kw9si9q
9 ай бұрын
tabnine?
@brettwestwooddeveloper
8 ай бұрын
Github copilot. It's $9.99/month. USD
why my session to be null when page refresh ?
@brettwestwooddeveloper
9 ай бұрын
Thanks for watching and to help diagnose your problem I would need more information.
@divajuni0406
9 ай бұрын
@@brettwestwooddeveloper after login success my page redirect to dashboard, and on dashboard page i console.log using useSession and i get the token from next auth, but when i refresh the page on dashboard the console log useSession token to be null, can you help me this issue
@divajuni0406
9 ай бұрын
And here i hit login api and the response of the api is jwt token only
Can you share the source code?
The timing is just too perfect.
@brettwestwooddeveloper
Жыл бұрын
I am glad I came in clutch
dude, good video about callback, but at the very beginning I thought you are going to teach us aerobic dancing...
source code, sir?
source code please ❤❤❤
@brettwestwooddeveloper, Thank you for providing a amazing tutorials, I am very grateful to you if you make another tutorial like how to reset and forgot password by email sending,Thanks again
i want to do this ( form with just phone number for login i send req to my api and api res a token and store it in session