I really like how you breakdown a complex concept in a step by step format. Especially the part where you talk about the three different ways of getting session data and their respective use case. It’s very clear and informative. Instant sub for me right there
This tutorial was on another level of prepared/concise. I like the showing multiple ways to do do protected routes, and the error notice related to loading bcrypt in the client bundle.
Thank you! I normally try to make the tutorials "error free" but some errors are so common they even catch me and I'm like "Oh yeah, this is definitely going to get someone else" haha.
This was a really comprehensive video on everything you need to get next auth set up. We're doing exactly the same thing in our enterprise SaaS. Currently exploring the new @auth package which next-auth is moving to, would be great to see you do an update video on this one with the new auth beta package (if you already haven't).
Great tutorial! Lots of good information in this video. I also like your presentation style. You never cover the user registration process so I will bring this tutorial down from 'ultimate' to 'almost ultimate' but it was still worth the watch!!
Haha, that's fair. Next-Auth takes the stance that registration is outside the scope of Authentication (which is true for OAuth). I created a video on making a custom register page that also covers saving the user with Prisma here: ruclips.net/video/HVFMc5Ac1F8/видео.html
@@simonhblanco Hmm, I'm not quite sure what you mean. Any user might be on your site and using multiple tabs -- some products use that flow heavily. The cookies are shared between all tabs so authentication should Just Work. Could you clarify what the problem is?
@@ethan_mick Thanks for the answer!!! and Yes you are right!!!. For a normal page, where people just log in to watch a movie, it's ok, but imagine a gambling site. two tabs open at the same time, it can be a problem ... users will try to make simultaneous transactions. or on a bank page. Can something be done in authnext to avoid that?
@@simonhblanco That's outside the scope of what Next-Auth can do. Here's my recommendation -- anything that needs to be protected from simultaneous requests needs to be handled in the backend (API route or database). Because if simultaneous transactions can break the site, people will make thousands of requests from bots and get around your tab protection. So it needs to be handled on your backend with server protection not client-side protection.
really, this was one of the best tutorial for next auth ever. u explained this content very clearly. thank u so much. i appreciate it and i would like u to go ahead and make video about api at crud process in next 13
This was the most in-depth tutorial for NexAuth with NextJS I have seen. Really great work, you explained everything very clearly. I have no doubt this chanell will blow up. Just wondering if you could maybe cover the T3 stack and how to handle redirects to a specified page when unauthenticated (instead of just to the signin page) and how you would use the credentialProvider with email and password with the T3 stacks session tokens. Thanks again for the great video.
Thank you! I'll add the T3 stack to my list and make some content around how to do those things. For handling the redirect when unauthenticated, you should be able to use `redirect` (server component) or the useSession hook and point the user to any page you want. I used the login page here, but it could be a different one. I'll make a followup video for creating a custom login page and show how to redirect to that.
Been looking for something like this for some time now, I'm glad I found you since this really explains everything I needed in great detail. Thank you :)
You are my Angel man ! Thanks for this excellent explaination, was stuck like 4 days with NextAuth but this video resolved my problem in just 40 minutes. Thanks thanks !
Really well thought out and well explained tutorial Ethan. Really helped with my understanding with setting up Next-Auth with the latest versions of Next :)
Hi Ethan! Really loved your series on setting up a NextJS app with Prisma, Postgres and Next-Auth. The way you delve into the background mechanics and offer contextual understanding is a huge plus for me! I'm not certain if this has been broached before, but possibly a video you can add to your backlog of ideas, is a video dedicated to handling dev/production environments. My primary intrigue lies in the nitty gritty of how to host a POSTGRES database and integrating it with the deployed NEXTJS app. One hurdle, i've been struggling to understand how to properly manage different environment variables and how to set it up properly for local vs production setups. Your insights on this would be golden! Or if you have any resources you could recommend on this topic, that would be super helpful too!
Just to chime in as I've also been wondering this, I originally hosted my DB locally using postgres but recently switched to Amazon RDS by suggestion of a developer friend, it integrates almost identically to how Ethan showed in his first video, and was relatively easy to set up in RDS. My DB seeding and migrations also worked seamlessly! This also would allow deploying the actually application to be done separately to the DB (Although likely done on AWS, but really anything would work with the RDS connection string). Not sure if this helped you at all, but I do recommend giving Amazon RDS a go as it has a great free tier and is very well received. Regarding your point about the env variables, for local dev/things you don't want to commit to prod etc you can use the .env.local file, but I must say I'm a bit fuzzy on that myself, someone else with greater insight might be able to assist there.
hi @@Mantenner, thanks for the recommendation. I'll definitely check out RDS. I've been playing around with .env variables for the last few days. Seems like there's a bit of a conflict on how Prisma and NEXTJS like to consume variables from those files.
Thanks for the kid words, and great idea! Having a good understanding of how the environments work, how to set them up, and how to use variables between them is a great idea for a video. I'll work on that!
Bro, Thankyou so much for the tutorial. Hope u have a good day, good life, and everything good because i could make a login page using credentials now. GOD BLESS YOU SO MUCH BRO!!!!!!!!!!!!!!!!!!!!
Thank you friend ......... the way you explain... now I have a clearer vision... before I understood it in a general way but you made me understand it step by step... thanks again Att. Jose Grillo
After days of frustration with JWT and session stuff, your video solved it! Massive thanks, subbed! Clear and concise. Would be awesome to do a video on how we can use custom User types (for TS stuff) for sessions. E.g. getting rid of the default “image” property etc
I appreciate you very much, you have a very good command of the subject and your expression is very clear. Could you please next tutorial using next-auth and next-intl together?
Nice video, learnt a lot. About the middleware though, what if we wanted to have other stuff as middleware? I tested it out and if I export default the other middlewares stop working. Do you have a video on that? Thanks.
I don't yet, but this is probably the trickiest thing when working with Middleware. I'll do what I can to make a video and try out a few ways. Do you have middleware you're using that you want to see merged together?
Also would love to see your thoughts and process on adding CSS in JSX when things like Material UI and Chakra UI catch up with the server components :) Thanks again!
thanks for the video, I saw months ago and now I had to use, best youtube video about nextauth. I' thinking how to implement "enable/disable" user access, maybe with short JWT expiration...
What an amazing tutorial! Could you explain (or maybe make a second video) about how to use Next Auth in a custom middleware (for example, a saas with custom subdomain settings)?
Yes! For my SaaS apps that are on subdomain (such as app.domain.com or dashboard.domain.com) I put all the Auth stuff *on* that subdomain as well. This means the cookies and everything will Just Work. If you don't do that, or you need to share the cookies across sub/domains you'll want to take a look at the Next Auth cookie options to configure all of this. next-auth.js.org/configuration/options#cookies
What if you wish to store the session in the database, regularly revalidate it, and, as a system administrator, have the capability to revoke access for a specific session? How would this be accomplished?
Hello when i tried to add in layout i have error function parseModel(response, json) { return JSON.parse(json, response._fromJSON); } do you know what it can means ? thank you
Hello, thank you for your reply. It is next 13.3 bug 13.2 is OK. But there is another problem when you first time sign in with credentials there is no session cookie in response so you have just token and callback cookies,…If you try to log again with these 2 coookis,…session is sent and saved,…you can try delete cookies and try to log in withou callback cookie. Do you know where can be the bug?
Note that the middleware.ts file should be "at the root or in the src directory (same level as your pages)" (see: docs). I have an src directory (not sure if this the preferred way to set up the project!), so it had to go in there, rather than at the project root as shown in the video. Thx for the video.
@@kristiankanya431 I personally don't use it because: 1. Most of Vercel's code doesn't, and if they don't do it, I didn't see the reason to 2. I like to keep my directory structure simple, so fewer is better 3. The `src` felt like it was legacy behavior and no longer necessary. That being said, if you like the organization it gives, that's fine! I prefer flatter directories, so I don't use it.
If anyone else has an issue with the middleware not securing the pages you specify, make sure the middleware.ts file is at the same folder level as your root page. For me this was in my /src folder.
Everything seems to work fine with the specific package version you provided, the only thing I couldn't get to work was the /localhost:3000/api route handler, when I was using the other 2 auth methods client side and server side, but when I used the middleware technique at the very end now /api seems to work.
Let's say you set up 1) traditional auth, 2) google oauth, and 3) facebook oauth in your app. When a user logs in with all three of these methods, how should the app determine that this is indeed the same user?
there is often a Session Model defined in the schema.prisma. Do you know what it does? What are the use cases for defining a Session model in the database
Great question. When you store sessions in the database, you are storing a secure token (the session token), the user ID, and an expiration. The client stores the token in a cookie or local storage and uses it on all requests. The server can then read the token from the request (often sent as a HTTP Header) and look it up in the database. You can then validate that 1) it exists in the DB, and 2) it has not expired. The benefit to doing this is you can delete a token from the database and it will invalidate all sessions using that token. For example, you have a "Log out of all devices" button for a user. When pressed, it would delete all tokens in the database for the user, so they are no longer logged in anywhere. When you use a JWT, there is no database session. Only the JWT itself defines the authentication. So you can't invalidate a session by deleting it from the DB. The benefit though, is that you don't need to make a roundtrip check to the database to validate the session.
Yes, you can add additional fields into the NextAuth configuration. They'll be passed into the `authorize` function that is called. Example: credentials: { name: { label: 'Name', type: 'text' }, email: { label: 'Email', type: 'email', placeholder: 'hello@example.com' }, password: { label: 'Password', type: 'password' } },
I really appreciate all your efforts in explaining these concepts. It's so helpful. But I do have a question about the client side session. It seems like all the extra info added isn't reflected on the session obtained via useSession(client side)?
Why didn't RUclips show me this yesterday when I was looking for exactly this??? I struggled with it all day, then managed to get it and now YouTuube recommends it to me. That's cyberbullying! Anyways, great video. Earned a sub!
friend thanks for the video, just one question... If I open 2 tabs of my app, with my active user.... He recognizes it for me in the 2 tabs... fine, but if I logout in 1 tab... the other one remains open... it only accepts leaving the tab, it only updates... and the serious idea is that it does so in automatic How should it be done using a useEfect or from the provider... Could you guide me please? Greetings Jose Grillo from Venezuela
Two thoughts: 1) This is how browsers work. When you logout of 1 tab it won't update another tab. However if the user tries to do an action (like click a button or create something) the request won't be authenticated and they will not be able to do it. I don't think you should worry about this use case -- don't fight the browser and just let your authentication do the work. 2) If you really want to update different tabs look into the developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API API which let's different contexts communicate with each other. When the user logs out of 1 tab send a message and listen for it on the other tabs. When that message is received, refresh/logout.
@@ethan_mick Thank you very much, I will check but your point of view is interesting ..... I will value it thanks Success brother... I'm still very aware of your channel... many blessings
I see some people have a prisma database query inside the JWT function to obtain some additional information about the user. Is that a good practice? if the jwt function is going to run multiple times, would it cause performance issues to have a database query inside?
I would not put database logic inside the JWT encode/decode functions, those are called way too often. If the database query is only on token creation that's probably fine, assuming the tokens live for a few minutes. The database should easily be able to handle a simple SELECT query like that.
Great job! Do you know what it means when I try to import PrismaClient? - Cannot resolve symbol 'PrismaClient' - I also have installed @prisma/client :O
Question I’ve been a bit stuck on , how would you handle if a user signed up with credentials previously but attempts to sign on with the same email using google provider ?
Great question! You can handle this 2 ways: 1. Just create a second user. Let users know that each way they login will make a different account. 2. NextAuth has a `callback` option that is called upon a successful login from OAuth. There is a parameter `profile` that is passed in that, for Google, contains the email. Use that email and lookup if you have a CredentialUser with that same email. Instead of creating a new user, finish the Auth with user from the database (use that primary key).
@@ethan_mick I wanted to just reject the user from signing in and let them know to sign in with the initial method of registration, I wasn’t sure how to achieve thisn
@@marxvision9874 If you throw an error in the `callback` the user won't be logged in and the URL will have a query `?error=err_text` where the `err_text` is whatever message your error had. You can add a custom error page to handle all these errors and tell the user what to do next: next-auth.js.org/configuration/pages#error-page
Amazing tutorial, thanks for the clear explanation. Have a quick question, I'm a little over halfway through the tut and have a seeded user in the database, my user shape is {id, first_name, last_name, role, email, password}. I can login but when inspecting the session I only get back the email field even though the shape of the authorize function return is the same as above. Can confirm the data in the database and the schema are in sync, and, if I return the found user before returning from the authorize function, I indeed get a full user with the shape above. Any reason that I might be only getting back the email in the session data from page to page?
Keep watching! I talk about this in the "Update Session JWT with new data" to show how you can add all the keys you want to your session object. Let me know if that doesn't make sense or you need anything else!
@@ethan_mick Thanks so much. I kept watching and it made more sense. I'm still a bit stuck though and even though I've implemented the casting of the User object in the authorize JWT callback as const u = user as unknown as User; I'm getting a login error. Basically the page loads from scratch and I log in, the JWT is loaded with correct data and the page then refreshes (next performs this for some reason) and then the user isn't available the second time and the subsequent session fields are undefined and a fail happens. Oddly though, the returned but undefined session in my console log for the session callback still contains fields I don't have in my User object. It feels like it's coming from the root class or object and not getting overwritten from my user fields. I don't have a 'name' or 'picture' field in my schema for User
I guess also to add to this, do I need to install the NextAuth Prisma Adapter? I'm not seeing the Accounts, Session or VerificationToken models in your schema
@@nuancetone That's only if you want to store sessions in the database -- for this (and a general recommendation), I use JWT's so no Prisma model is needed. It might be useful if you have many Oauth accounts setup, but I'm skeptical of so much black magic.
@@nuancetone Hmmm, without seeing the code it's a little hard to tell. Try the sample code (via description) and see if running that works for you, or how it might differ. And if you are using Server Sessions anywhere, you'll need to do something like this: github.com/ethanmick/time-tracker/blob/main/lib/auth.ts#L10-L14
Hmm, I pulled the latest code, updated all dependencies, and couldn't reproduce the error. Do you have the same error if you use the code in the repo? Do you have anything else going on in the component that uses getServerSession?
@@ethan_mick Just something that takes a jwt from the frontend and uses nextauth to verify and get decoded token, to give access to routes. I would be thankful if you used tRPC. 🙏
>>>>> UPDATE
build crud admin dashboard and midleware homepage please, i like your tutorial
Man don't stop making videos please, you explain so well and properly, we need more tutorials! :D
Hands down the best auth video about next and next-auth I've ever seen. You've got a new subscriber. Thank you so much!
Glad it helped you out!
I really like how you breakdown a complex concept in a step by step format. Especially the part where you talk about the three different ways of getting session data and their respective use case. It’s very clear and informative. Instant sub for me right there
Thanks! I try to think through the best ways to make a complicated topic approachable. Let me know if you have any questions!
This tutorial was on another level of prepared/concise. I like the showing multiple ways to do do protected routes, and the error notice related to loading bcrypt in the client bundle.
Thank you! I normally try to make the tutorials "error free" but some errors are so common they even catch me and I'm like "Oh yeah, this is definitely going to get someone else" haha.
This was a really comprehensive video on everything you need to get next auth set up. We're doing exactly the same thing in our enterprise SaaS. Currently exploring the new @auth package which next-auth is moving to, would be great to see you do an update video on this one with the new auth beta package (if you already haven't).
teaching and presenting skills are through the roof! THANK YOU! Instant subscribe.
If I start doing tutorials you’re the exact person I would be looking to emulate. GREAT job!
Wow, thank you!! That is such a nice compliment. I'm just doing what I can to help people out :)
You are really the best tutor I have ever seen . First video about next-auth that is complete thank you
Glad you think so!
this channel will blow up soon, sit tight buddies! Thanks for the info sharing mate!
Thank you! I'm just gonna keep making great content in the meantime :)
Great tutorial! Lots of good information in this video. I also like your presentation style. You never cover the user registration process so I will bring this tutorial down from 'ultimate' to 'almost ultimate' but it was still worth the watch!!
Haha, that's fair. Next-Auth takes the stance that registration is outside the scope of Authentication (which is true for OAuth). I created a video on making a custom register page that also covers saving the user with Prisma here: ruclips.net/video/HVFMc5Ac1F8/видео.html
There are a lots of tutorial but this is the best tutorial for next auth ever. !!! keep going like that.
Thank you so much!
@@ethan_mick Small question.. How do you avoid that the user open two or more tabs at same time. "Duplicate Tabs". ?
@@simonhblanco Hmm, I'm not quite sure what you mean. Any user might be on your site and using multiple tabs -- some products use that flow heavily. The cookies are shared between all tabs so authentication should Just Work. Could you clarify what the problem is?
@@ethan_mick Thanks for the answer!!! and Yes you are right!!!. For a normal page, where people just log in to watch a movie, it's ok, but imagine a gambling site. two tabs open at the same time, it can be a problem ... users will try to make simultaneous transactions. or on a bank page. Can something be done in authnext to avoid that?
@@simonhblanco That's outside the scope of what Next-Auth can do. Here's my recommendation -- anything that needs to be protected from simultaneous requests needs to be handled in the backend (API route or database). Because if simultaneous transactions can break the site, people will make thousands of requests from bots and get around your tab protection. So it needs to be handled on your backend with server protection not client-side protection.
Legendary mate, just finished up this one and your explanations are flawless as usual, can't wait to get onto the next one! This content is golden.
Thanks a ton!
really, this was one of the best tutorial for next auth ever. u explained this content very clearly. thank u so much. i appreciate it and i would like u to go ahead and make video about api at crud process in next 13
Thank you, I'm glad you found it helpful! Yes, I'll add that to my list and work on it!
This was the most in-depth tutorial for NexAuth with NextJS I have seen. Really great work, you explained everything very clearly. I have no doubt this chanell will blow up. Just wondering if you could maybe cover the T3 stack and how to handle redirects to a specified page when unauthenticated (instead of just to the signin page) and how you would use the credentialProvider with email and password with the T3 stacks session tokens. Thanks again for the great video.
Thank you! I'll add the T3 stack to my list and make some content around how to do those things.
For handling the redirect when unauthenticated, you should be able to use `redirect` (server component) or the useSession hook and point the user to any page you want. I used the login page here, but it could be a different one. I'll make a followup video for creating a custom login page and show how to redirect to that.
This is a great tutorial! You seem like a natural teacher and RUclipsr, please keep them coming.
Thank you! I'll keep them coming!
Been looking for something like this for some time now, I'm glad I found you since this really explains everything I needed in great detail. Thank you :)
Thank you! There's a lot here, but once you get it working it's so satisfying.
The way you are explaining everything is top notch, best tutorial I've found on RUclips, of course I've subbed!
Thank you! That means a lot 😊
by far the best App directory Next-auth tutorial to date. And you made it while the build was still in beta LOL.
Haha, I know, it still holds up pretty good! Thanks :)
You are my Angel man ! Thanks for this excellent explaination, was stuck like 4 days with NextAuth but this video resolved my problem in just 40 minutes. Thanks thanks !
Great to hear!
Thank you very much Ethan. I really like your fast forward pace. Much much appreciated
Thanks, haha. I didn't want it to take too long
In this week, I have been struggling to learn auth with next-auth and prisma. This has been super helpful, thanks a lot!
You're very welcome! I'm glad I could help.
I got phenomenal value out of this video ! Thank you, Ethan.
Thank you! You 10x my auth game .
Really well thought out and well explained tutorial Ethan. Really helped with my understanding with setting up Next-Auth with the latest versions of Next :)
Thanks! I'm glad I could help out :)
I'm looking for this video for several days, Thanks a lot!
I'm glad I could help! Let me know if you need anything else!
This video is extremely well done, and set me up perfectly for my webapp. Thank you, truly.
You're very welcome!
Great video man, found this in reddit and is just what I needed to handle users in my project!
Thanks, Reddit (for real). I haven't been super active since I don't want to spam self-promo but I try to make useful things. Glad it helped!
Hi Ethan, your videos are amazing 🔥💯
Thank you so much! I’m glad you like them!
you save my life.
the tutorial is super informative & easy to follow up.
Glad to hear that!
Hi Ethan! Really loved your series on setting up a NextJS app with Prisma, Postgres and Next-Auth. The way you delve into the background mechanics and offer contextual understanding is a huge plus for me!
I'm not certain if this has been broached before, but possibly a video you can add to your backlog of ideas, is a video dedicated to handling dev/production environments. My primary intrigue lies in the nitty gritty of how to host a POSTGRES database and integrating it with the deployed NEXTJS app.
One hurdle, i've been struggling to understand how to properly manage different environment variables and how to set it up properly for local vs production setups. Your insights on this would be golden! Or if you have any resources you could recommend on this topic, that would be super helpful too!
Just to chime in as I've also been wondering this, I originally hosted my DB locally using postgres but recently switched to Amazon RDS by suggestion of a developer friend, it integrates almost identically to how Ethan showed in his first video, and was relatively easy to set up in RDS. My DB seeding and migrations also worked seamlessly! This also would allow deploying the actually application to be done separately to the DB (Although likely done on AWS, but really anything would work with the RDS connection string).
Not sure if this helped you at all, but I do recommend giving Amazon RDS a go as it has a great free tier and is very well received.
Regarding your point about the env variables, for local dev/things you don't want to commit to prod etc you can use the .env.local file, but I must say I'm a bit fuzzy on that myself, someone else with greater insight might be able to assist there.
hi @@Mantenner, thanks for the recommendation. I'll definitely check out RDS. I've been playing around with .env variables for the last few days. Seems like there's a bit of a conflict on how Prisma and NEXTJS like to consume variables from those files.
Thanks for the kid words, and great idea! Having a good understanding of how the environments work, how to set them up, and how to use variables between them is a great idea for a video. I'll work on that!
Bro, Thankyou so much for the tutorial. Hope u have a good day, good life, and everything good because i could make a login page using credentials now. GOD BLESS YOU SO MUCH BRO!!!!!!!!!!!!!!!!!!!!
23:27 "Thanks Chrome, so secure."
Gets me every time 😄
Right?? lol
Thank you! This was an awesome tutorial. Keep 'em coming! 👍
Thanks, will do!
This channel should be subscribed! You are awesome in simplifying things.
Thank you so much 😀
exactly what i was looking for thanks you are a life saver
Thank's for this explicit tutorial !
This is wonderful and well explained
Thanks 👍🏼
Awesome guide Ethan! Love your work.
Thanks so much!
there we go! thank you so much for this! u are amazing
Heck ya! Glad I could help!
Awesome Nextjs, NextAuthjs tutorial. Keep it up
Thank you!
Now I need to change the my files 😂 I was waiting for this
lol, hope it’s not too much of a change!
@@ethan_mick no just some few changes but gonna get a clean files
Thank you friend ......... the way you explain... now I have a clearer vision... before I understood it in a general way but you made me understand it step by step... thanks again
Att. Jose Grillo
Thanks for the video! It was really helpful! 😀
OMG thanks Ethan... i already desperate learning about authentication
Glad I could help! It's a big subject with lots of nuance. Let me know how else I can help!
Excellent tutorial. Clear and concise, thank you
Thank you!!
thank you so much for the great job you do, greetings from morocco.
Thank you so much!
Really great content and explained really well
After days of frustration with JWT and session stuff, your video solved it! Massive thanks, subbed! Clear and concise.
Would be awesome to do a video on how we can use custom User types (for TS stuff) for sessions.
E.g. getting rid of the default “image” property etc
Welcome and thank you! I'll do what I can to make a video on that, I think it would be a great blog post too. Thanks!
The best video ive found on this topic. Im subbin!
Thank you so much!
I appreciate you very much, you have a very good command of the subject and your expression is very clear.
Could you please next tutorial using next-auth and next-intl together?
Thank you! I've had this request before, I'll add it to the list!
Nice video, learnt a lot. About the middleware though, what if we wanted to have other stuff as middleware? I tested it out and if I export default the other middlewares stop working. Do you have a video on that? Thanks.
I don't yet, but this is probably the trickiest thing when working with Middleware. I'll do what I can to make a video and try out a few ways. Do you have middleware you're using that you want to see merged together?
Also would love to see your thoughts and process on adding CSS in JSX when things like Material UI and Chakra UI catch up with the server components :) Thanks again!
Will do! I've been doing a lot of Tailwind for my Server Components which works very well.
Amazing explanation!
Thank you so much
You are welcome!
Nice nice nice... amazing video, thanks Ethan.
Thank you so much!
thanks for the video, I saw months ago and now I had to use, best youtube video about nextauth. I' thinking how to implement "enable/disable" user access, maybe with short JWT expiration...
thanks for the help. As I'm sure you already know, much of the docs and tuts are outdated. I was pulling my hair out trying to get this to work
Glad I could help! Yeah, I think it’s really helpful to step through all of these things end to end
What an amazing tutorial! Could you explain (or maybe make a second video) about how to use Next Auth in a custom middleware (for example, a saas with custom subdomain settings)?
Yes!
For my SaaS apps that are on subdomain (such as app.domain.com or dashboard.domain.com) I put all the Auth stuff *on* that subdomain as well. This means the cookies and everything will Just Work.
If you don't do that, or you need to share the cookies across sub/domains you'll want to take a look at the Next Auth cookie options to configure all of this.
next-auth.js.org/configuration/options#cookies
@@ethan_mick Please look into using middleware to protect pages with the prisma adapter. It does not seem to work for me :(
@@oamarkanji3153 are you using JWTs are database sessions?
Dude you are life saver man
You are amazing man 🍾
Great tutorial, thank you! :)
You are the best dude!
Well done Ethan, the guides you are providing are up to date and clear ! Thank you for your effort
Glad you like them!
Thanks for this awesome tutorial :)
You're very welcome!
Thanks a lot, amazing!
Can you advise where on the doc it is showing how to set up the providers.tsx with the new app router ?
What if you wish to store the session in the database, regularly revalidate it, and, as a system administrator, have the capability to revoke access for a specific session? How would this be accomplished?
Hello when i tried to add in layout i have error function parseModel(response, json) {
return JSON.parse(json, response._fromJSON);
} do you know what it can means ? thank you
Hmm, what code is that a part of? Did you make sure you have `use client` at the top of the file?
Hello, thank you for your reply. It is next 13.3 bug 13.2 is OK. But there is another problem when you first time sign in with credentials there is no session cookie in response so you have just token and callback cookies,…If you try to log again with these 2 coookis,…session is sent and saved,…you can try delete cookies and try to log in withou callback cookie. Do you know where can be the bug?
Note that the middleware.ts file should be "at the root or in the src directory (same level as your pages)" (see: docs). I have an src directory (not sure if this the preferred way to set up the project!), so it had to go in there, rather than at the project root as shown in the video.
Thx for the video.
Very true! I normally don't use the `src` directory, but this is an excellent point.
Do you think it's unnecessary? I wasn't sure. @@ethan_mick
@@kristiankanya431 I personally don't use it because:
1. Most of Vercel's code doesn't, and if they don't do it, I didn't see the reason to
2. I like to keep my directory structure simple, so fewer is better
3. The `src` felt like it was legacy behavior and no longer necessary.
That being said, if you like the organization it gives, that's fine! I prefer flatter directories, so I don't use it.
@@ethan_mick Good points made, thanks. I will work on altering it.
Nice content, thanks for this video ! 👏
Thanks, glad you liked it!
If anyone else has an issue with the middleware not securing the pages you specify, make sure the middleware.ts file is at the same folder level as your root page. For me this was in my /src folder.
Thank you so much for this!
You're so welcome!!
Thank you Next Auth for good guide.
Glad you liked it!
Everything seems to work fine with the specific package version you provided, the only thing I couldn't get to work was the /localhost:3000/api route handler, when I was using the other 2 auth methods client side and server side, but when I used the middleware technique at the very end now /api seems to work.
Glad it works at least at the end!
this is really helping me. thank you
Glad I could help!
Love you man! ❤
Thank you!!
Let's say you set up 1) traditional auth, 2) google oauth, and 3) facebook oauth in your app. When a user logs in with all three of these methods, how should the app determine that this is indeed the same user?
You can check to see if an email exists in the database. If it does you can return some type of message saying a user for this email already exists.
Or you can ask the user to link between these accounts.
Same what leetcode does.
there is often a Session Model defined in the schema.prisma. Do you know what it does? What are the use cases for defining a Session model in the database
Great question. When you store sessions in the database, you are storing a secure token (the session token), the user ID, and an expiration. The client stores the token in a cookie or local storage and uses it on all requests. The server can then read the token from the request (often sent as a HTTP Header) and look it up in the database. You can then validate that 1) it exists in the DB, and 2) it has not expired.
The benefit to doing this is you can delete a token from the database and it will invalidate all sessions using that token. For example, you have a "Log out of all devices" button for a user. When pressed, it would delete all tokens in the database for the user, so they are no longer logged in anywhere.
When you use a JWT, there is no database session. Only the JWT itself defines the authentication. So you can't invalidate a session by deleting it from the DB. The benefit though, is that you don't need to make a roundtrip check to the database to validate the session.
@@ethan_mick Thank you for your explanation
Super helpful! Thank you!
You're welcome!
Is it possible to have more than a email and password field? 4:47
Yes, you can add additional fields into the NextAuth configuration. They'll be passed into the `authorize` function that is called.
Example:
credentials: {
name: {
label: 'Name',
type: 'text'
},
email: {
label: 'Email',
type: 'email',
placeholder: 'hello@example.com'
},
password: { label: 'Password', type: 'password' }
},
Will the middleware strategy to protect the app wil also protect the API routes? Can we specify them in the config ?
what next version you use in video?
I really appreciate all your efforts in explaining these concepts.
It's so helpful. But I do have a question about the client side session.
It seems like all the extra info added isn't reflected on the session obtained via useSession(client side)?
Why didn't RUclips show me this yesterday when I was looking for exactly this??? I struggled with it all day, then managed to get it and now YouTuube recommends it to me. That's cyberbullying!
Anyways, great video. Earned a sub!
Thank you so much! Sorry you were struggling, auth can be a pain to get right!
Damn great content... This is damn great content
Thank you!
friend thanks for the video, just one question...
If I open 2 tabs of my app, with my active user....
He recognizes it for me in the 2 tabs... fine, but if I logout in 1 tab... the other one remains open... it only accepts leaving the tab, it only updates... and the serious idea is that it does so in automatic
How should it be done using a useEfect or from the provider... Could you guide me please?
Greetings Jose Grillo from Venezuela
Two thoughts:
1) This is how browsers work. When you logout of 1 tab it won't update another tab. However if the user tries to do an action (like click a button or create something) the request won't be authenticated and they will not be able to do it. I don't think you should worry about this use case -- don't fight the browser and just let your authentication do the work.
2) If you really want to update different tabs look into the developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API API which let's different contexts communicate with each other. When the user logs out of 1 tab send a message and listen for it on the other tabs. When that message is received, refresh/logout.
@@ethan_mick Thank you very much, I will check
but your point of view is interesting ..... I will value it thanks
Success brother... I'm still very aware of your channel... many blessings
I see some people have a prisma database query inside the JWT function to obtain some additional information about the user. Is that a good practice? if the jwt function is going to run multiple times, would it cause performance issues to have a database query inside?
I would not put database logic inside the JWT encode/decode functions, those are called way too often. If the database query is only on token creation that's probably fine, assuming the tokens live for a few minutes. The database should easily be able to handle a simple SELECT query like that.
thanks for great videos 🙏
Thank you!
Hi Ethan, do you have any updates on this?
THanks for the video, good job, but for some reason, my token in the session callback is always undefined :(
Great job! Do you know what it means when I try to import PrismaClient? - Cannot resolve symbol 'PrismaClient' - I also have installed @prisma/client :O
Great work, thank you
You are very welcome!
Question I’ve been a bit stuck on , how would you handle if a user signed up with credentials previously but attempts to sign on with the same email using google provider ?
Great question! You can handle this 2 ways:
1. Just create a second user. Let users know that each way they login will make a different account.
2. NextAuth has a `callback` option that is called upon a successful login from OAuth. There is a parameter `profile` that is passed in that, for Google, contains the email. Use that email and lookup if you have a CredentialUser with that same email. Instead of creating a new user, finish the Auth with user from the database (use that primary key).
@@ethan_mick I wanted to just reject the user from signing in and let them know to sign in with the initial method of registration, I wasn’t sure how to achieve thisn
@@marxvision9874 If you throw an error in the `callback` the user won't be logged in and the URL will have a query `?error=err_text` where the `err_text` is whatever message your error had. You can add a custom error page to handle all these errors and tell the user what to do next: next-auth.js.org/configuration/pages#error-page
Thank you very much ! You’re great thanks for ur feedback you have a new subscriber
@@marxvision9874 Thank you!!
Amazing tutorial, thanks for the clear explanation. Have a quick question, I'm a little over halfway through the tut and have a seeded user in the database, my user shape is {id, first_name, last_name, role, email, password}. I can login but when inspecting the session I only get back the email field even though the shape of the authorize function return is the same as above. Can confirm the data in the database and the schema are in sync, and, if I return the found user before returning from the authorize function, I indeed get a full user with the shape above. Any reason that I might be only getting back the email in the session data from page to page?
Keep watching! I talk about this in the "Update Session JWT with new data" to show how you can add all the keys you want to your session object. Let me know if that doesn't make sense or you need anything else!
@@ethan_mick Thanks so much. I kept watching and it made more sense. I'm still a bit stuck though and even though I've implemented the casting of the User object in the authorize JWT callback as const u = user as unknown as User; I'm getting a login error. Basically the page loads from scratch and I log in, the JWT is loaded with correct data and the page then refreshes (next performs this for some reason) and then the user isn't available the second time and the subsequent session fields are undefined and a fail happens. Oddly though, the returned but undefined session in my console log for the session callback still contains fields I don't have in my User object. It feels like it's coming from the root class or object and not getting overwritten from my user fields. I don't have a 'name' or 'picture' field in my schema for User
I guess also to add to this, do I need to install the NextAuth Prisma Adapter? I'm not seeing the Accounts, Session or VerificationToken models in your schema
@@nuancetone That's only if you want to store sessions in the database -- for this (and a general recommendation), I use JWT's so no Prisma model is needed. It might be useful if you have many Oauth accounts setup, but I'm skeptical of so much black magic.
@@nuancetone Hmmm, without seeing the code it's a little hard to tell. Try the sample code (via description) and see if running that works for you, or how it might differ. And if you are using Server Sessions anywhere, you'll need to do something like this: github.com/ethanmick/time-tracker/blob/main/lib/auth.ts#L10-L14
Amazing 🔥🔥
Thank you!
Great resource. I followed everything but getServerSession is giving me a dynamic header error. I also tested dynamic =force-dynamic
Hmm, I pulled the latest code, updated all dependencies, and couldn't reproduce the error. Do you have the same error if you use the code in the repo? Do you have anything else going on in the component that uses getServerSession?
Please make videos about deployments of that kind of projects, with migrations.
🫡 You got it
This works very well. Thank you
Glad it helped!!
What's that keyboard behind you?
Loved the content. Can you please make one with authorization too, instead of just authentication for the protected routes.
Thanks! Any particular style of Authorization? Eg, simple roles, RBAC, Policy Based Controls, etc?
@@ethan_mick
Just something that takes a jwt from the frontend and uses nextauth to verify and get decoded token, to give access to routes.
I would be thankful if you used tRPC. 🙏
I want custom login is pop-up with form login have many fields, how should i do ?
😮
Oooo, that's a good idea. I should make a a variation of this. What fields do you want in the login?
Well explained 👏
Thank you 🙂