Full Stack Authentication With Next.JS | Next Auth | Nest.JS

  Рет қаралды 44,216

Sakura Dev

Sakura Dev

Күн бұрын

📖 You will learn these:
✅ Protecting APIs in Nest.JS from Scratch
✅ Generate JWT Access Token and Refresh Token in Backend
✅ Integrate Next-Auth with Next.js 13
✅ Save and keep Backend JWT Access Token and Refresh Token in Next-Auth Session.
✅ Refresh Tokens automatically with Next-Auth in Server and client components.
✅ How To Use Next-auth callbacks
💖 My Twitter for more insights: / sakura_dev_web
🗃️ GitHub Repos: (Don't Forget to give a ⭐ to them on GitHub)
⭐ Nest.JS Project: github.com/vahid-nejad/FullSt...
⭐ Next.JS Project: github.com/vahid-nejad/fullSt...
📖Chapters:
0:00 intro
0:01:15 Create Nest.JS Project
0:01:44 Setup Prisma with Nest.js
0:03:04 Installing Config Module for Nest.JS
0:03:35 Creating User Model
0:04:44 Prisma Service
0:05:21 User Module
0:06:33 Create User Service
0:09:40 Hash Passwords
0:11:14 Auth Module
0:11:56 Sign Up API: User Register API
0:16:03 Login API
0:22:58 Generating JWT Access and Refresh Tokens
0:30:00 Create User Profile API
0:34:14 Protect APIs with JWT Guard
0:45:10 Refresh Token API
0:51:14 Next.JS Section
0:53:50 Setup Next-Auth with Next.js
1:01:04 Access Next-Auth Session with useSession Hook
1:02:28 SignIn Button Component
1:06:26 Session Type Correction
1:08:44 Using Next-Auth Callbacks for Keeping Backend AccessTokens in Session
1:14:34 Signup Page
1:17:45 Dashboard Page
1:18:45 Access Next-Auth Session in Server Components with getServerSession()
1:20:43 User Profile Page
1:21:57 Include Access Tokens in Http Requests to Backend Server
1:24:07 Protect Dashboard Page from UnAuthenticated User with Next-Auth MiddleWare
1:25:45 Refresh Access Tokens Automatically with Next-Auth

Пікірлер: 276
@SakuraDev
@SakuraDev 19 сағат бұрын
❤Please Support me by subscribing to my channel 👉🏻www.youtube.com/@sakuradev?sub_confirmation=1
@qunther
@qunther 7 ай бұрын
A masterclass. Your video is the most complete on KZfaq. Most of them always skip an important step, so their video become useless. You've made everything from A to Z, thanks a thousand time 🙏
@SakuraDev
@SakuraDev 7 ай бұрын
Thank you so much for your nice words 💞. I'm really happy that you like it 😊
@vinception777
@vinception777 4 ай бұрын
Hey thank you so much, you made this very clear to me, I'm using session and not JWT, but your content is currently helping me a ton to setup all this stuff ☺
@rahmatsulistio
@rahmatsulistio 10 ай бұрын
wow... this is the video I've been waiting for, thanks man
@SakuraDev
@SakuraDev 10 ай бұрын
Hope you enjoyed it!
@dionisidoksani7718
@dionisidoksani7718 5 ай бұрын
Amazing video tutorial. Everything explained and detailed to its core perfection!
@SakuraDev
@SakuraDev 5 ай бұрын
Thank you so much 🙏🙏🙏🙏
@tarek.k.hallak
@tarek.k.hallak 6 ай бұрын
Thanks a lot 🙏🏻🙏🏻 You have made it super clear.. and you managed to talk about i guess everything that related to authentication and authorization unlike other youtubers
@SakuraDev
@SakuraDev 6 ай бұрын
Thanks 🙏🙏
@jpcc1223
@jpcc1223 7 ай бұрын
i'm wordless, you helped me alot. thank you so much for posting this content!!!!
@SakuraDev
@SakuraDev 7 ай бұрын
Thanks 🙏🙏. I am really happy it was helpful for you
@user-hd3lx8qc7s
@user-hd3lx8qc7s 3 ай бұрын
good job bro ! A most comprehansive tutorial I've seen.
@SakuraDev
@SakuraDev 3 ай бұрын
Thanks 🙏🙏🙏🙏
@hc4382
@hc4382 8 ай бұрын
Very good tutorial, perfect u said a lot of things can not find in others tutorials, especially how to refresh the accessToken silently.
@SakuraDev
@SakuraDev 8 ай бұрын
Thanks, I am glad you like it 🙏
@SakuraDev
@SakuraDev 8 ай бұрын
@@michaeltrembovler8301 thanks 🙏 it was for the mic settings. I have fixed it.
@bhavikshah5869
@bhavikshah5869 Ай бұрын
This was insanely helpful for me. Thank you!
@SakuraDev
@SakuraDev Ай бұрын
Thank you so much for your support 🙏💓
@floviskabanda8044
@floviskabanda8044 5 күн бұрын
that is realy what i was looking for a while... thank you a lot
@SakuraDev
@SakuraDev 5 күн бұрын
Glad I could help!
@ekimcemulger8101
@ekimcemulger8101 9 ай бұрын
You are awesome as always :) ! Thank you.
@SakuraDev
@SakuraDev 9 ай бұрын
Thanks 😃🌹
@marcusvinicius1891
@marcusvinicius1891 6 ай бұрын
thank you so much! A real masterclass.
@SakuraDev
@SakuraDev 5 ай бұрын
You're very welcome!
@larrymcfarlane6202
@larrymcfarlane6202 6 ай бұрын
Not an easy transition to the NextJS section if you're following along with code, but if you can figure it out, hands down one of the best tutorials out there for refresh tokens for both client and server.
@SakuraDev
@SakuraDev 6 ай бұрын
Thanks 👍
@arieldebarros
@arieldebarros 6 ай бұрын
I'm also havind difficulties transitioning to the NextJS. It doesn't even build! How did you manage to follow along the tutorial?
@denvudd4492
@denvudd4492 9 ай бұрын
Thank you so much friend it's been really useful tutorial!
@SakuraDev
@SakuraDev 9 ай бұрын
I am really happy it was helpful for you😃🌹
@khangmach5369
@khangmach5369 Ай бұрын
Thank u, one of underrated awesome content out here.
@SakuraDev
@SakuraDev Ай бұрын
Glad you think so!
@gendev1105
@gendev1105 10 ай бұрын
Great Content ! Keep Up The Good Work !
@SakuraDev
@SakuraDev 10 ай бұрын
Thanks, you too! I am really glad You liked it.
@gendev1105
@gendev1105 9 ай бұрын
@@SakuraDev I am already watching it for a second Time ! keep up the Good Work ! Great Content
@jaychoi8821
@jaychoi8821 7 ай бұрын
This is .... damn! so goooood. thank you a lot ....couldn't help subscribing :)
@SakuraDev
@SakuraDev 7 ай бұрын
Thanks 👍
@PattyBeautCode
@PattyBeautCode 10 ай бұрын
I will also learn this Tutorial, The combination in this tutorial is awesome ! I see how amazing things NestJS can do ! I am still waiting for NestJS Postgres TypeORM, JWT Token, Key Cloak authentication, user role and OTP login !oo
@SakuraDev
@SakuraDev 10 ай бұрын
Hey, I am really glad you like it. Since I have not worked with Key Cloak, I need to do some research and find out how we can integrate it with node.js frameworks.
@PattyBeautCode
@PattyBeautCode 9 ай бұрын
@@SakuraDev I appreciated your replied, I like how you teach a lot. it simple and easy to understand for beginner, but I have given some intermediate task that not much good tutorial available form y usecase, you're kind of my last hope lol
@user-jf4qz4su3l
@user-jf4qz4su3l 9 ай бұрын
thanks bro you are the best teacher!
@SakuraDev
@SakuraDev 9 ай бұрын
Thanks 🙏👍, I am really glad to hear that from you ☺️
@_codesan
@_codesan 10 ай бұрын
Cant wait the next video
@SakuraDev
@SakuraDev 10 ай бұрын
I am really happy that you like my video. In the next video I will refactor the nest.js project and use Drizzle ORM for that. I hope you will like it.
@abdalrhmanalmarakeby5813
@abdalrhmanalmarakeby5813 27 күн бұрын
Thank you very much. This video was very helpful.
@SakuraDev
@SakuraDev 27 күн бұрын
Really glad it was helpful
@carlosbarbier2401
@carlosbarbier2401 5 ай бұрын
Amazing tutorial. Thanks a million
@SakuraDev
@SakuraDev 5 ай бұрын
You're very welcome!
@gamingwolf3385
@gamingwolf3385 10 ай бұрын
Thank you for this beautiful video
@SakuraDev
@SakuraDev 10 ай бұрын
Thank you too, Our pleasure!
@esquilo_atomico
@esquilo_atomico 2 ай бұрын
coming here again, very useful video
@SakuraDev
@SakuraDev 2 ай бұрын
Thank you so much 🙏🙏🙏
@CoreCave
@CoreCave 10 ай бұрын
Nice effort. we have learned a lot
@SakuraDev
@SakuraDev 10 ай бұрын
Thank you! I'm glad you learned a lot.
@allone258
@allone258 10 ай бұрын
Great job sir 👏
@SakuraDev
@SakuraDev 10 ай бұрын
Many thanks
@sithumdasantha3147
@sithumdasantha3147 9 ай бұрын
Thank you so much for the video
@SakuraDev
@SakuraDev 9 ай бұрын
Thanks 👍🌹🙏
@jalescollegelife
@jalescollegelife 6 ай бұрын
You're the best, Brother! Hope you have a wonderful life ahead of you!
@SakuraDev
@SakuraDev 6 ай бұрын
Thanks for your nice words 💖. I hope you do well ❤️‍🩹
@CoreCave
@CoreCave 10 ай бұрын
Thanks!
@SakuraDev
@SakuraDev 10 ай бұрын
Thanks a lot for your support. ❤❤🌷🌷
@eugenetsymbal2170
@eugenetsymbal2170 5 ай бұрын
Thanks for the great tutorial. I just want to make one clarification for those who are not familiar with JWT authorization. The refresh token must be implemented in such a way that it cannot be used more than once. And if an malicious user gets your refresh token and uses it, you will notice it immediately when you try to use it on your side. But in your implementation, if I understand correctly, the refresh token is reusable, since it is hardly possible to implement it without saving the token value itself to the database.
@sksabbirhossain2686
@sksabbirhossain2686 5 ай бұрын
best video ever. love from Bangladesh.😍😍
@SakuraDev
@SakuraDev 5 ай бұрын
❤️❤️
@BK-fk4gf
@BK-fk4gf 5 ай бұрын
Definitely great!
@SakuraDev
@SakuraDev 5 ай бұрын
🌷🌷🙏
@ego_dubovik
@ego_dubovik 8 ай бұрын
Hey, Thanks it's realy cool tutorial!
@SakuraDev
@SakuraDev 8 ай бұрын
Thanks, 🙏 I am really glad you like it
@chutikarnputtiwarodom8120
@chutikarnputtiwarodom8120 8 ай бұрын
Thank you so much!
@SakuraDev
@SakuraDev 8 ай бұрын
You're welcome! 🌷
@caresbruh
@caresbruh 5 ай бұрын
This is far better than those paid courses out there 😍
@SakuraDev
@SakuraDev 5 ай бұрын
I am really glad that you liked it 😊
@fluFFPfizschi
@fluFFPfizschi 10 ай бұрын
valuable tutorial! thank you
@SakuraDev
@SakuraDev 10 ай бұрын
You're very welcome! I'm thrilled to hear that you found the tutorial valuable. If you ever need more assistance or have questions, feel free to reach out. Happy learning!
@fluFFPfizschi
@fluFFPfizschi 10 ай бұрын
@@SakuraDev yes i have a question🙂 i followed your tutorial to the end and i pass the accessToken to the authorization header in the fetch() method. but its annoying to set the authorization header over and over again. do you know if we could set the authorization header on every request with the help of the middleware? i tried to implement it this way but i failed 😄
@SakuraDev
@SakuraDev 10 ай бұрын
@@fluFFPfizschi hi, if you're using client components, you can use axios interceptors. For server components, I recommend create a reusable fetchData func that only get API url. And then, in there call fetch func and set authorization header. And anywhere you need to fetch, just call fetchData func.
@anowarulhassan5117
@anowarulhassan5117 10 ай бұрын
Awesome👍👍👏😊😊
@SakuraDev
@SakuraDev 10 ай бұрын
Thanks for the visit
@andrechaves4116
@andrechaves4116 8 ай бұрын
thank you so much!
@SakuraDev
@SakuraDev 8 ай бұрын
You're welcome! 🌷🌷
@skkabirislam5934
@skkabirislam5934 6 ай бұрын
Amazing ❤❤❤
@SakuraDev
@SakuraDev 6 ай бұрын
Thanks 😊👍
@jeesan485
@jeesan485 9 ай бұрын
Thank you so much. your tutorials helped me on my own project. A project idea if its ok, users triggers long running job from client side seeing live status of the said job. Something that can handle lot of users kicking off long running job/script etc
@SakuraDev
@SakuraDev 9 ай бұрын
Thanks. Typically, Node.js is not good on long CPU intensive jobs. although, its performance on I/O intensive jobs is great. so it is better to use microservice architecture for this kind of jobs.
@jeesan485
@jeesan485 9 ай бұрын
@@SakuraDev interesting, do you know any example repo i can look at? my main goal is to run playwright.js browser automation scripts
@en_kratia
@en_kratia 7 ай бұрын
Thank you very much
@SakuraDev
@SakuraDev 7 ай бұрын
Thanks, I hope it was helpful
@_codesan
@_codesan 9 ай бұрын
Terima kasih.
@SakuraDev
@SakuraDev 9 ай бұрын
Thank you so much for your support ❤️🙏
@davithchhung7577
@davithchhung7577 9 ай бұрын
Nice video!
@SakuraDev
@SakuraDev 9 ай бұрын
Thanks for the visit
@hooyah
@hooyah 3 ай бұрын
thanks for the video 🙏🙏❤❤, I was curious how to handle role base authorization, at 1:25:07, you created middleware only for those who have sessions, but what if I have a dashboard for users and a dashboard for admin or maybe a dashboard for sellers? I like the way you solved the refresh token problem. I usually use axios interceptors like you taught me in the past.
@esquilo_atomico
@esquilo_atomico 2 ай бұрын
🤗Obrigado amigo! Você é um amigo!
@SakuraDev
@SakuraDev 2 ай бұрын
Thank you so much. It means a lot to me 🙏❤️
@lucasdindault417
@lucasdindault417 5 ай бұрын
Hey ! Nice video! I've just got one question: how do you ensure that, on the Next side, the user is automatically logged out when their token expires?
@danimusbar
@danimusbar 7 ай бұрын
tks for your kindness sharing this nestjs, this is i am looking for.. please make another video full stack using nest js and next js, like marketplace or airbnb or linked in.. tks
@SakuraDev
@SakuraDev 7 ай бұрын
Thanks 🙏, I will do that
@milesrykerodazie171
@milesrykerodazie171 9 ай бұрын
Thank you so much for this video.I have done authentication with cookies using nestjs and using the api with nextjs 13.on my local host , it works very well and sets the cookie and persists on page refresh.but when i deployed the nestjs api the cookies does not set at all.the login is successful but the cookies dont set.I have tried several solutions but i still get same issue.any idea on how i can go about this? i will really appreciate help on this.Once again thank you so much
@waltervanwoudenberg6876
@waltervanwoudenberg6876 9 ай бұрын
Monorepo with nextjs + nestjs using drizzle and next-auth with the drizzle adapter would be cool video to watch. Where both next and nest share this drizzle db
@SakuraDev
@SakuraDev 9 ай бұрын
Ok, This is a nice suggestion. I put that in my list
@Valentim_Gab
@Valentim_Gab 4 ай бұрын
When the session expires and the tokens refresh, if you don't press F5, it keeps calling the API thousands of times and when the Refresh expires it gives a lot of errors.
@tronaitor0
@tronaitor0 3 ай бұрын
Briefly skimmed through the vide and it look like exactly, what I was looking for. Just had a quick question, my backend for user authentication is developed in Django, but this will be the same right? Thanks!
@SakuraDev
@SakuraDev 3 ай бұрын
Hey 👋. Thanks 👍. Yes the nextjs part is the same.
@kellslte
@kellslte 7 ай бұрын
I love this tutorial! I have been looking for something like this but then I have an issue. I started following the tuorial as I did not have any issues on the backend setting up the things I set up but then I had serious issues with the Next.js next-auth. I am hitting the endpoint but then I am not getting results. I have tried to log the response to see what it contains but then I see nothing in the console. I suspect that it does not log anything because the page refreshes everytime I enter the credentials. Also my return object from the backend is different yours in the video but I was under the impression that I should be able to customixze it to do what I want to, but back to my question, what do you think could be the reason for this?
@leobaldoneto
@leobaldoneto 2 ай бұрын
Check about the useSession. If you are using the NextJS 14 with server components, it will not work.
@andranikhambardzumyan6264
@andranikhambardzumyan6264 4 ай бұрын
Thanks
@hamzahix4860
@hamzahix4860 8 ай бұрын
thank you
@SakuraDev
@SakuraDev 8 ай бұрын
You're welcome 🤗
@roktimashraful2085
@roktimashraful2085 8 ай бұрын
Sir , your tutorial was amazing, i have an one question, my question is when you try to refresh the token at that point is it possible to clear the session with sign-out and redirect to the login page?
@myrddral11
@myrddral11 8 ай бұрын
Point on. Just tested: in case of invalidated refresh token, the user session remains valid. I could even navigate to routes assumed protected.
@roktimashraful2085
@roktimashraful2085 8 ай бұрын
Yeaa , and even i con't call logout function in server component also ,
@ernestsdane3510
@ernestsdane3510 5 ай бұрын
That is the nature of JWT auth. There is no real way to honor the user's request to sign out (to invalidate a JWT token) because of this the users are going to stay logged in until the access token expires. In order to solve this issue, you are going to have to look to session based authentication (also known as cookie-based authentication). Because you can save the session tokens in the database, it is very easy to de-authenticate the users - just delete the session token or mark it as invalid.
@tarek.k.hallak
@tarek.k.hallak 6 ай бұрын
With this implementation if i provided a correct token i can Access any endpoint with all the ID's.. that means that i can access any profile i want if i have its id
@SakuraDev
@SakuraDev 5 ай бұрын
That's right, we should have done some extra validation for that, for example we can extract the id of the user from the access token and authorize the user to get the profile if it is its own profile.
@guilhermecfialho
@guilhermecfialho 8 ай бұрын
Hi there, Nice video... but i have a question, when you navigate into other tabs and came back, it really does the refresh token, but it does not work well while navigation into others routers and reloading page (f5, and others reloads methods) there is an method to solve this problem, to when it reloads the page it does the refreshToken, if accessToken expired? I know in other video that you made, it works but in the client side, but i want to know if there is an way to do in the server side, thanks
@angHoangAnhQuan-kb9yq
@angHoangAnhQuan-kb9yq 4 ай бұрын
Hi thanks for the video, I have a question, at the 47:17 mark in the video, I have an error that "Parameter 'req' implicitly has an 'any' type." so it's really an any type or something other type? I'm fixing it by add ''@Request() req: any" but do you have any better idea?
@HuyNguyen-ix4bl
@HuyNguyen-ix4bl 9 ай бұрын
i have a question , we have the api for auth using nestjs why we must do the nextjs server api ? is this because the next-auth package want it that way ? i never use the next auth package so i need some explain about that
@angHoangAnhQuan-kb9yq
@angHoangAnhQuan-kb9yq 4 ай бұрын
Hi, I have a question. The refresh token is only use when you reload the page or re-login. What's happen if the access token is expired then you call an API without reload the page? I'm so confused, please help me awnser this. Thank you!
@sulavbaral9972
@sulavbaral9972 9 ай бұрын
Hey can you make a video with both google and oauth provider like google with capabilities of storing both of these in a database
@Everydaycono
@Everydaycono 9 ай бұрын
Thank you so much this video is awesome I have a question. at the 1:41:30 mark in the video, there's a question about how to hide the session information that appears in the network tab every time you access the web, specifically the "GET /api/auth/session" request, which shows session details such as user and backendTokens. Is there a way to conceal this information? The reason for wanting to hide it is that the token values are being exposed. Do you have any advice on this matter?
@SakuraDev
@SakuraDev 9 ай бұрын
Yes, but it isn't a big deal because if the user is not authenticated, it is not shown in the network tab. Thanks 👍
@Everydaycono
@Everydaycono 9 ай бұрын
@@SakuraDev thank you!
@ngaji_it
@ngaji_it 7 ай бұрын
@@SakuraDev How about XSS issue?
@hasanulhaquebanna
@hasanulhaquebanna 10 ай бұрын
Appreciate your dedication! I have a question about the token stuff! In real-world projects I think, refresh token stuff works like when accessToken expires then again call for access token (till refresh token not expire), and when refresh token expire then user should logged out meaning need to login and new refresh token add. But in your case, it's not working like that, may I know why?
@SakuraDev
@SakuraDev 10 ай бұрын
Exactly. My solution is following that approach. Is there a problem with that?
@hasanulhaquebanna
@hasanulhaquebanna 10 ай бұрын
@@SakuraDev I think you're doing that with client side, because i didn't get any of that idea properly from backend! That's why get confused, plus you didn't send any token in cookies through backend
@SakuraDev
@SakuraDev 10 ай бұрын
@@hasanulhaquebanna there are two approach for authentication in backend. Stateless which uses jwt and stateful which uses session in backend. You are talking about session based auth and I talk about stateless auth.
@hasanulhaquebanna
@hasanulhaquebanna 10 ай бұрын
@@SakuraDev thank you so much for clarification but with jwt we can also get both approaches right? That is what I tried to say
@SakuraDev
@SakuraDev 10 ай бұрын
@@hasanulhaquebanna yes we can use both. 🙏👍
@saifhaq4998
@saifhaq4998 6 ай бұрын
Awesome Tutorial........... Can you make one with GRAPHQL please
@SakuraDev
@SakuraDev 5 ай бұрын
Put it on my list
@alemendieta3346
@alemendieta3346 4 ай бұрын
Great tutorial! How can i implement both Credentials and oAuth providers in Auth.js, but with my backend logic in NestJs? That is, store my users in DB, but only NestJs can read/write database?
@SakuraDev
@SakuraDev 4 ай бұрын
Hi thanks 🙏. About your question, yes we can it is little different. Actually I am planning for creating a video about it.
@kubilaybzk
@kubilaybzk 10 ай бұрын
İ have a small and important question. We have an api that lists one product. We will ensure that the products are listed by using this api in the admin panel. Let's assume that we get the token information thanks to NextAuth, so we need to use it in the api as headers: {Authentication: 'Bearer {token}'}. When the page is first loaded, NextJS does not know what this "token" information is, so it crashes while fetch. And the products unfortunately do not appear on the screen. Is there any chance we can do this without putting a talk like if(token) ?
@SakuraDev
@SakuraDev 10 ай бұрын
Hi, It seems you are fetching your product in a client component. I would recommend to fetch data in a server component and the create a loading.tsx page in the same level of that page and then inside the loading just render a spinner or a loader or... The next.js will show the loading page, while your data if fetching
@matheusdesousamenezes514
@matheusdesousamenezes514 9 ай бұрын
Wonderful tutorial! I would like to ask a question that i couldn't understand in the NextAuth docs: Lets say that we have two computers: "A" and "B". - I log in with with my account in computer "A" - Then i log in with the same account in computer "B" I understand that computer "B" should have the refreshed token, and computer "A" should have it's own token as invalid (therefore the refresh endpoint would give an error). But how does NextAuth deals when the HTTP call inside the refreshToken function gives an error? Does it erases the cookie? Sorry for the bombarding of questions, and again, many thanks for the tutorial! EDIT: I think the problem of my question is more about the business model of the api (if the backend allows two active tokens at the same time for example), but i still would like to know what should happen if that refreshToken gives an error hehehe
@SakuraDev
@SakuraDev 9 ай бұрын
Hi, In this project, the backend does not keep track of the jwts, so it allows multiple valid jwt as far as they are valid and not expired. if you want to keep track of active jwts, you should store them in a db when you are creating them.
@ozdadev
@ozdadev Ай бұрын
In your components you have manually added the Bearer totken which is not a easily maintainable approach, what if refresh token in invalid?
@pirterm
@pirterm 7 ай бұрын
Very nice tutorial. I tried to follow up the client side with Next-Auth, cause my authentication backend is already running in ASP. I noticed one issue, and maybe you can explain what is going on. When I authenticate, I'm having correct user data, access token, refresh token and expires in values, till the first refresh call. Refresh endpoint returns correct data, and the same way I'm returning new token with modified backendTokens, but then on every jwt callback, there are still the same values. So it keep refreshing token on every request. But what funny is, when I use getServerSession in Server Action, there the token is correct (refreshed one). So I ended up refreshing token on each and every request after first one expires. Has anyone noticed anything like that before?
@eriksund1369
@eriksund1369 2 ай бұрын
At 1:23:44 when you refresh it still has the username in the sessions (top right). How is a good way to have all of this updated as well when the accessToken expires?
@noureddein8044
@noureddein8044 4 ай бұрын
Thanks alot for the amazing videio but now what will happend if the refreshToken expired? How I can force the user to logout ? That the main issue i faced when i tried many times to implement the NextAuth.
@wervana
@wervana 7 ай бұрын
How to use Google Provider with it? Client is not sending password to check the authenticity of the user.
@youngming7752
@youngming7752 6 ай бұрын
Good video except that you left out an important part: Checking if the refresh token is expired. In a comment below u mentioned that you should just call the sign out function in this case but inside the jwt callback it is not possible to call that function. Yes you could run it inside the protected page but that is also not practical if there are multiple protected pages. Then there is also the middleware.ts but when calling the sign out function there and redirecting the user, a window is not defined error is being thrown...
@SakuraDev
@SakuraDev 6 ай бұрын
Thanks for bringing that to my attention 🙏
@youngming7752
@youngming7752 6 ай бұрын
​@@SakuraDevI found a very simple solution for this. We can include the "session" option in inside [...nextauth].ts right after the "callbacks" option. There we set strategy to jwt and maxAge to the same lifetime that we specified for the refresh token in the custom backend. The session lifetime and refresh token lifetime will be synchronized that way. If the lifetime for the refresh token is 7 days (and session maxAge 7 days) and the user visits the page after 7 days, the session (from the session option) will be expired and the user will be logged out. Hope this helps anyone having the same issue
@youngming7752
@youngming7752 6 ай бұрын
There is also another big issue: When reloading a page manually the jwt callback is being triggered, but the jwt callback is not being triggered on page transitions. So if the user stays on the same page until the access token expires and then e.g. submits something using a button click, he will provide the invalid access token because it has not been refreshed. I also figured out a solution for that which includes using the refetchInterval option from the SessionProvider component
@rorn-dev
@rorn-dev 9 ай бұрын
i have a question. like we know next auth is default to 7d but when we use refresh token like this that back end token will more than 7d right . so if the nextauth session was expire what happen here ?
@SakuraDev
@SakuraDev 9 ай бұрын
so you want the backend tokens to be expired when next-auth session is expired?
@rorn-dev
@rorn-dev 9 ай бұрын
@@SakuraDev no. coZ back end refresh token is keep refreshing so it is mean that the time of refresh token is keep longer and longer . back to our next auth session we just use the default to 7day so this point it will not sync . what i want is to make sure that next auth session is expire when the refresh token is expire to keep it sync i hope you get my purpose
@phongngo315
@phongngo315 9 ай бұрын
Hello Sakura Dev, today I watched a lot of videos of you. But I still have some questions, please help me :((. I'm building a fullstack website with NextJS. I'm using NextAuth for authentication. And now I can login by credentials and some third app, but I want to have a jwt token to middleware protect when success logged in. But in my session, I don't have any jwt token. How can I achieve it or Do I have to do it? Is safe when return the id in the session? I have tried to return the public information of user in session, and they id I save in jwt, is that right?
@SakuraDev
@SakuraDev 9 ай бұрын
Hey. So you want to protect some pages with next auth middleware?
@phongngo315
@phongngo315 9 ай бұрын
@@SakuraDev Yes, I want protected my post api, because I return the user id in session, so I nervous that can be got by somebody, and they can do a post api
@mahers8172
@mahers8172 9 ай бұрын
awesome ! but I got issu when I refresh the token for the first time it's work but then will refresh secend time it's send the same old refresh token
@denvudd4492
@denvudd4492 6 ай бұрын
Hey, can you please make the video where you combine custom credentials and Google Provider for example? It works cool for now, but in my app, I want to add OAuth and I can't figure out how I need to combine these 2 flows. Like we need a password for user creation, right? Do we need to create a separate model for OAuth users? Thank you again friend!
@Maulanafb
@Maulanafb 6 ай бұрын
Yeah
@vanithb6630
@vanithb6630 9 ай бұрын
Bro I have a doubt.. while call api.. if api is facing error how to handle it
@JoãoBisinotti
@JoãoBisinotti 6 күн бұрын
what about the deprecation warnings for bcrypt dependecies? You didn't get that on your installation but I saw more people with this issue
@SakuraDev
@SakuraDev 6 күн бұрын
I will upload an update for this video
@Maulanafb
@Maulanafb 6 ай бұрын
hello sakura how to authenticate nextjs with nestjs backend with oauth nextauth
@helpsleepingrelax3071
@helpsleepingrelax3071 9 ай бұрын
Sir, how to handle it if the refresh token is not expired, it will log out automatically
@arieldebarros
@arieldebarros 6 ай бұрын
Great tutorial! How do we generate random SSL Keys on Windows machines?
@SakuraDev
@SakuraDev 6 ай бұрын
Hi, You should install open ssl on your windows machine and then run this command: openssl rand -hex 32
@mohit84604
@mohit84604 9 ай бұрын
Sir its almost second week. When will the video wiith drizzle come
@nitishdesigns4210
@nitishdesigns4210 5 ай бұрын
I have one doubt. How to logout user when refresh token is expired?
@sudam-d
@sudam-d 10 ай бұрын
Hi, There is a small issue with the current Nextjs setup. Say that an endpoint is going to be hit on a button click in client side. If the token has expired, the jwt callback does not get called. It gives a 401 unauthorized. Any suggestions on how to fix it? I apprecaite your content. ♥
@SakuraDev
@SakuraDev 10 ай бұрын
Yes that's one of the edge cases. let me see how I can handle that. I will let you know. BTW thanks for bringin that to my attention
@muhammadusama7121
@muhammadusama7121 9 ай бұрын
@@SakuraDev Any update on this ? or do you have any suggestions how it should be handled. So I might look into this as well.
@SakuraDev
@SakuraDev 9 ай бұрын
@@muhammadusama7121 Hi, In the next week I will come up with solution.
@dimashiskenderov498
@dimashiskenderov498 9 ай бұрын
@@SakuraDev Awesome video, but for my project I have stumbled on the same issue. I found your older video where you manually update session, should I use that approach when hitting 401 on client side? kzfaq.info/get/bejne/iLacY9VevtKaoIk.html
@sudam-d
@sudam-d 9 ай бұрын
HI, I came up with a solution. Let me know whether you need me to share the code to have a look!
@asadmehboob1300
@asadmehboob1300 10 ай бұрын
can we save user records from Next Auth google provider to nestjs and then database?
@SakuraDev
@SakuraDev 10 ай бұрын
Yes we can. In next auth events and callbacks we can do that. In my next video I will do that.
@asadmehboob1300
@asadmehboob1300 10 ай бұрын
@@SakuraDev ty great
@michaeltrembovler8301
@michaeltrembovler8301 8 ай бұрын
I 'd faced the problem of CORS Error when sends POST request by await fetch(Backend URL + "/auth/register" {...}) from the client side. Will be very thankful for answer.
@tayutai1616
@tayutai1616 7 ай бұрын
I solved that problem by adding `app.enableCors()` to main.ts of Nest.js project.
@OnlyJavascript
@OnlyJavascript 10 ай бұрын
why use nest for back-end? is this for educational purpose or next can't handle back-end services?
@SakuraDev
@SakuraDev 10 ай бұрын
Next.js can handle backend services. But for scale projects, definitly, you need a powerfull backend framework like nest.js.
@OnlyJavascript
@OnlyJavascript 10 ай бұрын
@@SakuraDev thank you sir.
@johnkucharsky6927
@johnkucharsky6927 9 ай бұрын
@@SakuraDev what is so powerfull in nestjs? next can handle all this easily. If you don't use backend for other projects, you can use next
@SakuraDev
@SakuraDev 9 ай бұрын
@@johnkucharsky6927 for example , with nest.js you can easily create microservices.
@TemmyCodingLifestyle
@TemmyCodingLifestyle 8 ай бұрын
Thank you for your response. But Sometimes, the tokens might be good but the user has been deactivated while logged in, which will cause the user profile to be 401. At that point, I'd like to log the user out. Please how can I achieve this? Cause at that point, the user is still authenticated but the profile details getting are throwing a 401 error. Thank you for all you do.
@SakuraDev
@SakuraDev 8 ай бұрын
In such cases, you can use the "sign out" function from next auth
@TemmyCodingLifestyle
@TemmyCodingLifestyle 8 ай бұрын
@@SakuraDev I can't call signout as a function or use signout in my [...nextauth] route . Maybe I'm not doing it well tho
@ahmedf2
@ahmedf2 8 ай бұрын
in min 22:00, why you didn't provide the hash salt (which you set to 10 breviously) while comparing the given password and the stored password hash? N.B: here is the code snippet I am asking about : await compare(dto.password, user.password)
@SakuraDev
@SakuraDev 8 ай бұрын
Hey, when comparing, we don't need to pass the salt rounds.
@ahmedf2
@ahmedf2 8 ай бұрын
@@SakuraDev why, isn't the salt affect how the hash output will look like?
@SakuraDev
@SakuraDev 8 ай бұрын
@@ahmedf2 Really nice question. The compare function's role is simply to check if the two hashes match. The salt and the number of rounds used for hashing are known and stored with the hashed password, so there's no need to specify them in the comparison function.
@minhtimus
@minhtimus 9 ай бұрын
Hi, if i want to add another provider (like google, github) then how can the access/refresh token be generated and sent to the backend?
@SakuraDev
@SakuraDev 9 ай бұрын
Hi, you can do it in next auth events
@ssatriyaa
@ssatriyaa 9 ай бұрын
@@SakuraDev This one is quite confusing. Please do this one (google provider with nextjs and nestjs) in your next video. Thanks
@akshaygunshettiwar7080
@akshaygunshettiwar7080 9 ай бұрын
Is it compulsory to install python while installing the dependency bcrypt? Repeatedly giving me the error find python
@SakuraDev
@SakuraDev 9 ай бұрын
I am on Linux and python is installed by default. So I can't tell you that this is necessary or not. But I don't think it needs python.
@jonyonee
@jonyonee 9 ай бұрын
Hi, can we please have a video on how to make all routes '/admin/**': { ssr: false }
@jaspreetmaan121
@jaspreetmaan121 8 ай бұрын
How can I add google-provider with this method
@SakuraDev
@SakuraDev 8 ай бұрын
I am going to create a video about it,
@rodrigogr9358
@rodrigogr9358 9 ай бұрын
My dashboard page is not protected, i can access without a session, what can it be?
@SakuraDev
@SakuraDev 9 ай бұрын
Hey 🖐🏻, maybe you did not configure next-auth middleware or you did not set matcher in middleware.
@mohit84604
@mohit84604 10 ай бұрын
Sir when will the vidoe with drizzle orm iwth nest js come
@SakuraDev
@SakuraDev 10 ай бұрын
Hi, In the next few day I will Upload that.
@molinar1974
@molinar1974 9 ай бұрын
How to proceed (delete session) when refreshToken is expired
@SakuraDev
@SakuraDev 9 ай бұрын
Just call signOut func form next auth
@alirezak5870
@alirezak5870 9 ай бұрын
my jwt is encoded should i decode it with this logic to get exp time? or nextauth grab it itself?
@alirezak5870
@alirezak5870 9 ай бұрын
when i get my token expire time from session console log the expire time is more than one month but our laravel backend developer said the expire time is 5minutes and also after 5minutes api get unauthorized in rtk query but session is exist in cookies is it possible the jwt config in backend have issue?
@alirezak5870
@alirezak5870 9 ай бұрын
im get stucked in nextauth i do all the video but im not sure the exp time is coming from nextauth randomly or my jwt token time is incorrect :(
@SakuraDev
@SakuraDev 9 ай бұрын
Hey! if you encode your jwt in backend side, you should decode it in the backend side. next auth session just keeps it. you should set exp time in the backend side.
@alirezak5870
@alirezak5870 9 ай бұрын
@@SakuraDev I struggled a lot with it and in the end I used the verifyJwt method again and realized that the problem is with the browser's time display. i converted the time to iran standard time zone session expiration works correctly based jwt exp time that i assigned in async session.expires after decoding but browser expires and maxage is a fake number and i think its gmt and i believe this issue can be a bug or missed browser time zone settings.
@alirezak5870
@alirezak5870 9 ай бұрын
i mean session time is correct but numbers stored in cookies are incorrect but based jwt time you conveted in auth options session removed
@ChibuezeLawsonLoctech
@ChibuezeLawsonLoctech 9 ай бұрын
Hello Sakura Dev. I keep getting this error. Kindly assist: "Nest can't resolve dependencies of the UserService (?). Please make sure that the argument PrismaService at index [0] is available in the UserModule context." it happens once a save this constructor "constructor(private prisma: PrismaService) {}
@SakuraDev
@SakuraDev 9 ай бұрын
Hi, you should register Prisma service in the provider list of user module and also auth module.
@ChibuezeLawsonLoctech
@ChibuezeLawsonLoctech 9 ай бұрын
@@SakuraDev Thank you, sir.
Dependency injection fundamentals in C# - DI vs IoC vs DIP
13:30
Amichai Mantinband
Рет қаралды 25 М.
Пробую самое сладкое вещество во Вселенной
00:41
We Got Expelled From Scholl After This...
00:10
Jojo Sim
Рет қаралды 74 МЛН
small vs big hoop #tiktok
00:12
Анастасия Тарасова
Рет қаралды 24 МЛН
Next-Auth on App Router - Solid Auth, Super Fast
17:20
Jack Herrington
Рет қаралды 103 М.
NestJs Authentication : Login, Signup, Refresh Tokens, JWT, Guards
58:19
DRIZZLE ORM - Connect NODE JS app with POSTGRES Database
20:49
Easy Next.js & NestJS Authentication with Clerk
33:23
Michael Guay
Рет қаралды 5 М.
Пробую самое сладкое вещество во Вселенной
00:41