NextAuth Tutorial | Part 1 - Setup and Email Provider

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's up guys it's your boy leo and i'm back with another next.js tutorial and today we're going to be looking at the popular authentication library called next auth so let's get into it [Music] so if you're not familiar with what next auth is it's pretty much an open source library that allows you to easily set up authentication for your next js application it allows you to set things up like social logins such as google github facebook with ease you can also set up passwordless email logins as well as credentials login if you want to set that up it's pretty flexible so it's kind of built to run on serverless as you can see here from their flexible documentation but you can bring your own database so it does provide you with a bunch of different adapters for things like postgres mongodb prisma and things like that and it's also pretty secure it kind of handles the csrf token validation as well as jwt and gives you a bunch of different options and to allow you to kind of customize your authentication solution all right and first thing to note is that we are going to be using the version four and we're gonna be setting this up for version four it's currently in beta but there are quite a bit of breaking changes between version three and version four so i didn't really want to uh create a tutorial for the current version version three just to have it kind of become obsolete here in a couple of weeks or months or depending i don't think it'll be months because it's currently in version two of the beta so um that's kind of why i decided to go with version four and so yeah let's get started with our project all right and so if you've been following along or if you've watched any of my other tutorials you know that i kind of create these uh projects within github and i'll have different branches for the different parts of this tutorial so i plan for this tutorial to be four different parts the first part we're gonna be looking up how to set uh next auth up as well as using the email provider where the part two we're going to look up how to do the social provider as well as credentials providers so credentials provider is username and password social is using oauth apps like github or google then for part three we're going to look up how to set up our custom our own custom sign-in page as well as how to utilize uh custom callbacks as well as custom events and then part four we're going to look at how we can quickly leverage react query which is a library that i personally really enjoy using so if you're already using react query you can leverage this library to be used with react query so all right let's get started with part one and to get started what we're going to do is we're first going to uh add two libraries here so we're going to be adding the next authentication library and again since uh version 4 is in beta we do need to specify the specific version beta.2 seems to be released five days from me filming this so we're going to be using that version and then we're also going to be adding the node mailer library here and the node mailer library is pretty much is going to act as our transport protocol to be able to send emails for the user to actually be able to log in so if you're not familiar with what password list email login is it's pretty much instead of doing the comment username and password what happens is you put in your email when you go to kind of log in that then generates a email that gets sent to your email and then once you click sign in then you're able to log in so that kind of uh helps mitigate a lot of the attack vectors that username and password emails uh kind of introduce and i think it's kind of the future for uh new applications um just because it does uh minify kind of like that attack vector possibilities and we do have to now explicitly also add node mailer so if you are familiar with this library at all but version three node mailer was part of the dependencies that it came with so you didn't have to manually install it note 4 they removed that but you do need to now um manually explicitly install that if not you won't be able to send that email so once we've done that i'm going to be also using uh prisma for my database adapter for this tutorial just because i already kind of have that set up locally from my other tutorial so it'll be a little bit easier for me to show you guys what's going on with um uh the database and how the kind of user table the account table session table all that thing works with this next auth library and so that all kind of happened pretty quick so the libraries that i just installed for prisma are the prisma client and i also installed the next off prisma adapter so in version 4 you do need to explicitly install whatever the adapter for the database that you plan on using is for this example i'm going to be using prisma and then you also do need to make sure that the version is the next version um if you do not uh add this part it seems that there are quite a bit of issues i don't know if it's because of the beta version of version four but um when i was using just a primary adapter like that i was not able to get it to work correctly um so adding the at next gives it a different version and then it's all working swimmingly and another library that i just installed that i didn't in the previous was the prisma library so also just make sure that you add prisma to your dev dependencies and let's just make sure that that was added yep that was and so now we should be ready to go to set up prisma and so to set up prisma what i'm going to do is i'm going to actually create a prisma folder and then within this folder i'm going to create a schema.prisma file and then within this file i'm going to kind of copy the documentation or pretty much what i get from the next auth documentation for the uh schema for prisma and pretty much what it's doing is it's just setting up a postgres db uh we're getting the prismaclient generator over here and then it kind of comes with these models for our different tables so we're going to have a account model so that's going to just create a account table for us we're also going to have a session table we're going to have a user table so this will kind of keep track of the users for us as well as a verification token which is pretty much that uh it tracks the verification token for different users and so with those uh models created for us um and if i went by pretty quick uh let me show you where you can actually get that information so if we go to their documentation and we go to their adapters here you can quickly go here to mongodb or not mongodb oops uh prism adapter and here you can see um if we go to yarn it tells you what libraries had again make sure that you do add the at next version here um i don't know if that will be fixed for the main version of version four but for now if you are using the beta version uh make sure that that that is how you add it and then here is that file so schema.prisma you can go over here and just quickly copy it don't i didn't make any changes to it this is pretty much exactly copy and paste so just a heads up and so once we've done that the next thing that we're going to do is we need to create some environment variables for our different providers and for our prisma setup to work so like we need to create an environment variable for that database url so what i'm going to do is there is this next off example um let me see if i yeah let me zoom in a little bit so this next auth example is a example pretty much in their next auth.js library and it has this environment.local.example and i'm just going to copy and paste this so pretty much what it has is just a bunch of different ids and secrets for different providers and things like that and i don't really want to manually write that out so what i'm going to do is i'm just going to copy that and i'm going to put that as my example here so there we go and then what i can then do is as you can see here we have this database url but here in the example is using sqlite but i'm going to be using a different style so i'm going to add that to env and then i'm going to configure this to work with my local postgres so i guess while we're here we can actually just kind of add a couple more environment variables that we're going to be using for the rest of this tutorial and so the ones that i'm going to add is i have this next auth url um this is kind of just nice to have for production uh deployment so i'm just going to add that i don't think i actually use that in the tutorial but just so you guys know that you can use that um and then for the database url i'm gonna change it to use my postgres so if you're familiar with the postgres connection strings pretty much just need to add my username password localhost and my table name here um the secret here you can see it's kind of just a bunch of just gibberish but i'm just gonna do uh uh super secret for now and we'll just keep that as our secret but again make sure that this is kind of a long randomized string when you do do this this is just for the tutorial um the email server so this is kind of where it gets a little bit interesting so if you're not familiar with what smtp is smtp is a pretty cool little tool and let me see if i can just uh look up the quick definition for you guys and so pretty much smtp is just a mail transfer protocol that allows you to kind of just send a mail through other mail servers so for example i can utilize google's smtp server to send uh automated emails from code without really having to spin up or using a kind of like a spin up like a send grid or set up my own kind of protocol or anything like that it kind of allows you to send i think 500 emails a day i think is the limit so it's pretty decent um so yeah so that's pretty much what smtp is and so i'm going to be using my personal gmail here and so i'm going to then add my username and my password for whatever the gmail account is i'll walk through how to actually set this up in your google account as well and then um here we can also see that we have this gmail.com make sure it's 587 that's the port that you need to do for uh ssl and then pretty much um email from we have next auth and yabish and so this is pretty much just who this email is going to be from when we send it via smtp and what we need to do in order to allow this smtp email to be sent uh for our gmail for example is we do need to actually turn on this less secure app access so this allows you to kind of um programmatically call your smtp server and send an email um again this is a little bit dangerous so be careful with this but for this tutorial i'm just going to be using that and then i'll turn it off after so yeah so you can find that in your google account and then the security tab less secure app access and then you just turn that on and then you should be able to programmatically call your smtp server cool and so i've gone ahead and added those uh values to my.env and then now we should be able to create our next auth database in our postgres so what we're going to do is in order to do that first i'm going to call the npx prisma generate so this is pretty much going to generate a prisma client based off of this schema.prisma for us so it's going to go ahead and load that one thing also to know is that i am using env sometimes in xjs it's kind of recommended to use env.local i just didn't really want to go through the figuring out how to call from.env.locals but so if you try to do that and you're running into issues that it can't find as database url it does look uh by default in env so just a heads up on that and so once we add that then we can actually run our migration so um this is going to go ahead and actually create that database for us um and let's see what happens oh i already have a database so i'm going to just pretty much just um kind of just rerun it and erase all the database information that i had while i was trying to test this out and so there you go and so now you can see that we've generated the prismaclient and if i go to pg admin and start that up you'll be able to see that we now have this next auth database here and then if we go into the schema and the tables here you can see that it kind of creates this account session user verification token uh let me zoom in again for you guys and so yeah so created that next authen so this is the database that was going to be used to kind of handle all of our authentication with next off and so now that we've kind of had all of the resource generation kind of complete let's go ahead and actually start adding some next auth implementation details and so what we're going to do is in the source file here in our api we're going to create another folder called off and within this folder we're going to have a catch all route called next auth and then we're going to name this.ts and then we're going to go ahead and kind of again i got this from kind of if we look at this next auth example here and oh let me go back if i go to the example and we go to pages api um auth next auth here you can see that i kind of get the uh example from this but this is using version three so i have done a little bit of changes to make it so that it does use version four but if you want to you can always go to their next auth example library to kind of see how to work with that um so yeah so now that we know where we got that information from let's look at what we're actually doing in this file so this is kind of the tell all file for how to kind of set up your different providers your adapters all the information that you're really going to be using with the next auth library and so let's look what's actually happening in this file right now so we're pretty much just of course importing the next off so that we're going to export default next off uh with a bunch of different configurations and then we have we're importing the email provider so email provider is that way that i mentioned that you actually instead of logging in via like username and password or social connection what will happen is that you'll probably type in your email you'll click send uh uh sign an email you'll receive the email you click the link in that email to sign in and it's kind of a little bit more secure than username and password so i really enjoy using it um then we're also gonna import some prisma stuff so we're gonna import the prisma adapter as well as the prisma client and then we're going to be creating that object and using all of this information to make sure that we can actually set up this email provider correctly and use prisma as our adapter for our database so that's pretty much all we're doing here so we're pretty much just setting up like telling our next author we're going to be using prisma as our database adapter we're also telling it that we are going to set up an email provider and then we do have a email server from and then uh or email server and email server from and again this is just your smtp server and email from is just like who you want the email to display as so you can kind of make this whatever you want again i set those up in the environment variables and um yeah and so then another thing that we do is down here we're also going to be setting up a secret and again if you remember i think i just set it up to a super secret but again this should be a reasonably random long string it's going to be used to kind of sign your cookies as well as to encrypt your jwts so make sure that it's actually pretty strong for this tutorial i didn't really make it that strong and then another thing is for session so we're going to be using jwt and it's automatically set to true but if you do kind of set a database i think this is actually uh like version three stuff because the database option no longer exists you do need to use a database adapter so i guess we can get rid of that but you can see here that we do have jwt is true we are going to be using jwts for our sessions and then you can kind of go ahead and actually add some more details to your jwt for now i'm not really going to mess with it too much just a simple tutorial but their documentation kind of gives you all these different options that you can actually use to kind of customize it and then we also see here that we have access to pages so this pretty much is you can actually define custom pages so there are a couple of default pages that next auth comes with so for example the slash sign in sign out the off error a verify request page as well as a new user page i do believe this is null but you can we'll actually go ahead in part three of this and actually see how we can use it utilize that as well as callbacks and events and then we also can change the theme from light to dark and you can also enable debug messages uh to make sure everything is working correctly and then with that set up we can actually start going ahead and modifying our application to work with our um session provider from next auth so in version four or version three used to be next odd slash client version four is next off slash react so that would have been one of the breaking changes and so and then the other one is i think it was provider and now it's session provider but they pretty much act very similar um so pretty much what we're doing here is we're pretty much just importing session provider and then we're going to wrap our component in this session provider and this will allow us to use different session hooks such as use session and get information with regards to next off throughout our application and now let's start up our application and it should be good to go so once we enable that let's see how it builds we can actually go ahead here let's go to localhost 3000 and it's gonna take a little while because of the first initial compile and cool so you can see that we have our default uh page here and let me make sure that's at 150 okay so yeah so this is kind of the default page that we have just defined in this index i didn't really change it from the default stuff we will go ahead and change that here in a little bit but what i wanted to show you guys is if i go and navigate to auth slash sign in um oh that's because i need to make it api sign in you can see that we're presented with this default sign-in page that uh next auth actually provides for us and that's pretty cool but now let's actually change our index page to kind of automatically navigate to this on a login button click and so what i'm going to do is go back to our index.ts here and i'm going to go ahead and actually uh modify this a little bit to do that for us so what we can actually do is we can actually import these uh so next auth slash react kind of does come with a couple of different uh client apis that we can use so if we go to their documentation and you go to their client api here you can see a list of all the different things that we can use so for example we have access to this use session hook which pretty much just lets us it's the easiest way for us to check to see if the user is currently logged in so just check their session and again that's why we need to make sure that we wrap our application in session provider then we also have access to things such as get session get csrf token the sign in call the sign out yeah sign out call and it tells you whether or not you can use this on the client side or server side so that's really cool so that's pretty much all we're doing in this page here we're importing uh use session sign in and sign out and then we're going to be using that use session hook to make sure like hey let's see if the user is actually logged in and what the status of this generating this getting the session from the current uh states is and so we pretty much check like hey is it loading to see if whether or not the session exists um so you can have different types here and i think it is yeah authenticated loading and unauthenticated so pretty much what we do here is if status is loading just display a loading page if session exists meaning that they are logged in we're going to tell them who they're logged in as by displaying their email and then display a sign out button that on the click just signs the user out and if they're not signed in we pretty much just let them know that hey you're not signed in would you like to sign in with this button which on click will just call the sign in method here and so now if we go ahead and just go back to our default page you can see here that the quick loading and so we're not signed in right now and what is this zoom on it's okay 150. so if i click sign in you can see that it automatically uh pretty much redirects me to this api auth sign in and then it also has this callback url so that the callback url is pretty much going to tell this uh login saying like hey when this user actually successfully authenticates redirect them to this callback url so it'll take me back to the index page so that's pretty cool so let me go ahead and put in my email so documentation nerds gmail.com and sign in with email and so when i click that button in the background it's going to go ahead and actually do all of that node mailers creating the email send it to me things like that and you can see here that we also have this verify request page which is one of the default pages that next provides pretty much just saying like hey check your email to see to make sure that you can actually log in and so let me go into my gmail.com and let me go to yeah so here you can see i received that authentication email and so like sign in to localhost 3000 here as you can remember we this is what we sent our from email to be as well as uh sign in as documentation nerds gmail.com if i click sign in you can see now that i'm actually signed in so it went ahead and actually did all of these things to be like wait you can't sign in until you actually verify from your email that you're allowed to sign in so that just it's kind of in a weird way like a one-time password so that's pretty cool and what i mean by one-time password is like if i go ahead and click sign in again uh you see it's uh no longer valid so that's kind of like what's happening in the background here is that it's checking to see hey is this sign in league still valid or not and you can customize how long this link is actually uh available for and the way to do that i think is you can actually go into the next auth here and if we go to our email provider you can see that there's a bunch of different things or customizable options that you can add so i think the max age default is 86400 which i think is a day so that's so that means the verification link is going to be available for a day and then you can also actually customize how you want to send that verification email so you can actually create a custom method and provide different options um so you can use a different transport so for example if you want to use a popular like send grid or something like that you can actually do that within here and define it within here you can also change um how to uh how this email looks so if you remember this is kind of the default email but what you can actually do is if you go to their providers here and let's look so you can see there's a bunch of different uh providers that they come with and they give you pretty decent instructions on how to do that but if we go to email you can see that we can actually uh customize how the email looks so for example here they're creating an entire html body and then you can kind of create this like template for how your login email should look like so that's pretty cool but for the sake of this tutorial i'm not really going to go into that just to kind of make it a little bit uh simple but what i am going to do is i want to show you guys how this is affected within our database so now that we've actually successfully logged in if we go and we see our uh information in this user table you can see that i have this uh email documentation at gmail.com and since we are using email verification it also handles setting this email verified them for me being like hey they're email verified that's the only way they can log in right so that's pretty cool um and then another thing is this verification token table um so this is what gets generated um you can see that it's empty right now and that's because we actually went ahead and verified but if i go back to let me see here and let me sign out but if i sign in again with a documentation nerds gmail.com and let's just resend that email um so here what should happen is within this verification table there should now be a identifier and so pretty much what this is saying is like hey there's a verification email out there or a verification token out there for this specific user that hasn't been accepted yet so you can see that it gives us this expiration time stamp so that's i think used for later on if i go let's say wait the whole 24 hours or maybe in a week come back and click that link it'll check against this be like oh no this is expired and then not allow the user to uh log in and so yeah that's pretty cool let's go back to my emails here and you can see that it was sent again and uh yeah so let's log in here again and there we go so now i'm signed in as documentation gmail.com and what happens when you actually successfully authenticate so let's look at applications here and uh pretty much what you can see is that we're setting a cookie and this is this next auth session token that's pretty much getting set and this is just a jwt so if you want to you can actually copy this value and go to jwt.io and paste it in here and you'll be able to actually get information as to what that uh um pretty much is kind of what that looks like right so you can see here this pretty much just telling um our next session is just storing information like hey this is what the user identifier is when this session token expires when it was issued at as well as the email that it belongs to so these are all just information that i believe next auth will actually have available and you'll actually have availab this information available to you whenever you kind of call you session or get session so that's pretty cool you also have uh pretty much this callback url cookie set as well as the cisrf so this is just um just some added security and if we look at local storage uh you can see here that there is an actual message pretty much just saying like hey get session it's just an event so that's pretty much what's happening in your application whenever you do successfully authenticate and to kind of further uh run this uh just to kind of give you guys some more uh information with regards to this library let's actually go ahead and create a couple of api tokens so i want to kind of show you guys how you can create a let's say for example a token.ts route and so what this is going to do is pretty much just going to be a jwt kind of um just a way for you to actually generate a token kind of whenever you want so that's pretty cool so what you can do is from uh next off you can actually import they do have a jwt folder so you can just import i do believe you actually need to change it for version four so it does need to be import star as jwt and then we're just going to import of course just the default kind of next um api route stuff and so what we're doing is we're pretty much just getting a token so we're just going to wait uh jwt dot get token so this is one way to kind of add a protected route is we're going to be able to see if in the request are they able to actually generate this token and if they are then we send the token if they're not then we just kind of sent undefined back to them and this does some things under the hood with your request such as like getting your session from your cookies and things like that so now if we go back and we navigate to let's just do slash api token um you can see here that it pretty much gets this uh token for us but if we actually were to be i'll show you guys what happens when you're actually logged out uh later on but we're gonna do a couple more things that i want to show you guys what happens when you're authenticated um another thing that we can do is that there is actually a api session which again this is a built-in uh route from nexjs that kind of gives you session uh information if you ever want to access that so that's kind of cool um and so yeah so let's build another route to show how to use a protected route using the get session call as opposed to using the jwt get token and the way that we do that is let's actually just go ahead and create another api route and we're just going to call this one secret.ts and we're just going to paste this in here and so here you can see that i had my notes still using version 3 but i went ahead and changed it for version 4. um but yeah so pretty much what we're doing is you actually have access to this guest session which if you uh remember when we quickly looked at the client api that this call is actually callable from the uh client side as well as server side so pretty much what you can do is you can actually go ahead and call this get session using the request so again this probably just checks to see like hey does it have a session cookie in its session and if it does then we return a session meaning that like hey this user is actually authenticated and if it doesn't then we say like hey you're actually not authenticated you can't access this route so if we now go to slash api secret we should be able to see like yo what's good that's just because this user is authenticated so we're good on there and last thing that i want to show you guys before i show you guys what happens when you're not authenticated with those routes is i actually want to create a new page for server side rendering and show how you guys can actually get the session cookie on using nexjs get server side props so what i'm going to do is i'm going to create a server.tsx page to kind of resemble uh doing that in server-side rendering so again i'm using client here so this needs to be react so yeah so let's change that to react and then pretty much what we're doing is we're having this interface for session which is just going to have this session object from our uh next auth library and then pretty much all we do is i got this from that next auth example it's just some just some text saying like hey if you actually are logged in we're gonna show you that you're actually uh supporting server-side rendering with authentication and then if you're not then we're saying like nah it says you're not logged in but then here you can see that we can actually utilize this get session called as i mentioned on the server side to actually pass in the context with get server-side props contacts what i'm assuming happens the same thing it checks to see whether you have a session cookie in here and if you do it returns it and if it doesn't it'll be null and so pretty much here we can set that this session will either be session or null we can provide it into our page props and then we can check it in here so if i go ahead and let's navigate to server page you should go ahead and you can see that uh it's actually authenticated because it's showing me this server-side rendering message so let's go back and actually log out and then show you guys what happens when we navigate to all three of those routes while we're not actually logged in and so if i click sign out pretty much what that does is it will just call the api sign out which is again a built-in um callback for this next auth library and so now that i'm not signed in let's try to access all the different things that we've been playing around with so if i go to session you can see that it's an empty because i'm not logged in if i go to let's say it was api token you can see that i do get null because again i'm not logged in so i can't get a jwt if i go to secret you'll see that hey stranger danger we don't know who you are you're not logged in you're not able to see that and then if i go to our server page you can see the server says you are not logged in so you can see that you can actually use uh this library pretty easily to uh protect your api routes as well as protect certain pages just using the get session so the way that i like to think about it is i use use session whenever i need to pretty much have a react functional component that i need to access the um kind of uh so for example in this page here we're using use session so if you're able to use use session hook i recommend you do if you're not because you're calling it in the back end or just maybe not within a functional component use get session so that's kind of just how i like to think about it and yeah that's pretty much how to quickly set up email provider as well as looking into how to kind of set up a couple of nice little uh index pages so you can kind of play around with uh the next auth uh client api as well as setting up our uh pretty much prisma database adapter and just a this next off page which is kind of like the bread and butter of the app that you can go ahead in here and then you'll be able to provide all the different ways that you want to allow your application to actually uh authenticate so that's pretty much a quick little setup as well as a quick little information about this library is honestly a great library and i've really enjoyed using it and plan to use it pretty much for any application that i do use next js so um yeah so that's just a quick part one of this tutorial and i hope you guys enjoyed it and if you did please leave a like comment and subscribe and then i hope to see you guys in to see you guys in part two where we'll look into how to add social providers as well as the old-fashioned uh credentials provider which uses username and password so uh hope to see you guys in the next one thanks [Music]
Info
Channel: Leo Roese
Views: 739
Rating: 5 out of 5
Keywords: next.js, next, typescript, javascript, authentication, authorization, nextauth, NextAuth.js, Next-Auth.js, react, session, jwt
Id: C6eH6zsPgSk
Channel Id: undefined
Length: 33min 17sec (1997 seconds)
Published: Sun Sep 12 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.