How To Send A Verification Email using Next-Auth - Step by Step (Detailed)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's up YouTube today we are going to learn how to create a verification token so we can send it to our users who are registering onto our application what this essentially does it allows us to make sure the end user has access to the email and also to verify that email by us sending a randomized token to their email they click on it and it verifies their email you've probably seen this all across the web and today we are going to do it using next js14 we're going to do styling with tailwind and saten we're going to send the email with resend and then we're also going to use aujs version 5 for the authentication so if this sounds interesting to you hit that like button and also subscribe for more content just like this but other than that let's get started and let's get coding okay so let's jump into my screen so I have actually already coded a bunch of the code that isn't related to the verification token so as you can see here we have a register page and a login page and we are using shat and Tailwind for The Styling and it is functional we created two server actions one for the login and one for the register so this register is actually working we can actually register a user and it gets sent back to our mongodb database and we're using prism as the urm so the code will be inside the description of this YouTube video in a GitHub repository so if you do you could just clone that code and follow along but like I said we have already created the UI just to get that out of the way because the tutorial is not about the UI it's more about the verification token and now let's jump into the code real quick and let's look at some of the code that we already created so the first thing I want to do is show you how we configure off JS version 5 so if we actually jump back to the browser and we go to the docs we need to install this package right here so it says npm install next- beta make sure you install this package and this allows you to use aujs inside of your application let's go back to our code and then there's three other packages you just want to install right off the bat because you're going to have to use them that's if you're using prism which will be the RM so if we go to our package Json the other packages we're using is on line 12 which is at o/ prism D adapter so make sure you install that package and you could write it exactly how it says right here that's how you install this package another package you should use is the app prism client online4 and the other package you need to use which is going to be dab dependency is going to be the prism package and there is docs for prism and those are what those three packages are and this allows us to connect the database to our actual application so make sure you have those four packages that went over installed onto your application okay so the next thing I want to go over real quick is configuring the O which I already did and like I said either copy the code from the GitHub link or you can pause the screen and copy the code like that but the first file you need to create when configuring your aujs version 5 is an .ts file and this is going to be on the root layer of your application so as you can see we have off TS file and what essentially this does is it defines your authentication this is your pretty much entry index file right here so what we have to do at the top is we have to import next off from next o and we have our prism adapter in here we also have our database as you can see this is my database and if I go to this file this is where I initialize my prism client which allows us to use methods and query methods into our database so this is a file you want to copy you don't want to keep calling the prism client in every file you want to do one file and then export it as whatever variable you want which I named a database and in this file as you can see we are defining our handlers which we're using G and post requests those are the request types that next off requires us to call we're also defining the O which allows us to essentially get the session from the user that's logged in on whatever page we want that is the new way of doing it in version five we have the sign in and sign out functions here too which they are what they pretty much say sign in is going to allow you to sign in and then sign out will sign out and this is going to equal the next off object and inside this object this is where you can Define your asynchronous callbacks we are also going to spread through these Al config right here so we are going to create another file which I'm going to show you in a second and this is going to be all of the stuff in that off config file that we're creating we also have to define the session which is going to be of strategy JWT and then we have our defining our adapter which is the prism adapter and then we're just passing in that prism client invocation right here which is that database that we imported at the top okay so that's your RS file in a nutshell and that is on the root file root layer of your nextjs application next one you want to create is your A.C config.sys you're going to want to use you define it in here and the reason why we're defining in here is because prism is not compatible on the edge and if you are using an orm that is compatible on the edge you can actually Define your provider in the .ts file but this separates it even better just organizes the code a little better and it's just one extra file on the root file layer which is the A.C config.sys ality code in here and then this is where we're exporting it and then this is how we imported it here at the top as Au config and then we spread through the syntax of all of the data and props inside of that right here in the au. TS file so that is why it looks like that so there is an alts off config and then the last file we need to configure your OJs is inside of the app directory and then it needs to be inside of an AP folder and then inside of a off folder and then inside of a catchall route which has a syntax of brackets and then dot dot. next O So as you can see here top left and then inside there is a route. TS file and it is Lally one line of code we're just exporting those handlers which are going to be the get and post and that is coming from that Au TS file so those are your three files you need to configure OJs we also went over the UI of how our application BS like I said copy that code from GitHub or create your own UI and also we are like I said using server action so I have a login server action which is on the server and this allows us to log in and then we also have a register server action which allows us to register our user to our mongodb database so that is a quick overview of what we're going to do now let's actually jump into the verification proc of how we can actually create a verification token using OJs Okay so so those packages from Prism that I told you to install they should be installed and what that did for you was it would create a prism folder for you if you did it successfully so we have a prism folder and inside that we have a schema. prism this is where we're going to be able to define the data that we are sending to our database so as you can see we already have a user model which I created and you create to and has an ID a name email and password and there is going to be one one thing we're going to add to this and it will be a email verified so that's going to be the first step and what is going to be is it's going to be a date time and it's going to be optional so it's not going to be required it is going to be optional for the user because some applications will require maybe yours like a Google provider login so we don't want to make the email verified to be pretty much um necessary or or required we want to make it optional so we're going to have this question mark so we want to store this in the user so we could use this later to actually see if they're allowed to log in or not so that is the first step inside the prism schema next thing we want to do is we want to define a model for our verification token so we need to create a verific verification token and send it to the database but we need to create how the token is going to look so we could call this model verification token or whatever you want and what we're going to have here is we're going to have an ID of string I'm just going to use what copilot's showing me and then adjust stuff as needed so we have an ID of that decorator which is for mongodb only so whatever database you're using go to the prism docs and see what this decorator should be but this is The mongodb Decorator for an ID next thing we need to have is we want to have the email that is going to be a string then we are going to have our token we can remove the user ID and we can remove the created app and we want to have an expires and the reason why we want to have an expires is because this verification token should expire after a certain amount of time this verification token shouldn't be um pretty much valid forever and that is very common across all web applications okay so the next thing you want to do too is you want to make sure we're going to add this decorator which is at unique and what this essentially does is is going to make sure that the email and the token having a unique combination so we're never going to have the same email with a token or token with email or vice versa it's always going to be unique so that is what this line right here is doing line 30 okay so now we have created our verification model and the next thing you want to do is every time you make a change on your schema. prism file you want to make sure you open the terminal shut your development server down if it's running run npx prism generate and this will update this model to make sure it connects with your database and I always just like doing npx prism DB push just to make sure everything is synced in line with your database and prism so that is the first step in the verification token process step two is actually generating or creating the token so what we are going to do is inside of our lip folder right here we're going to open this and let's create a new file called token. TS and let's actually create this token so we can use it so first thing first is let's create a function and this is going to be an asynchronous function let's just name it generate verific a token and what we're going to set in here is we're going to set the email so we need the email when from when we register the account so that's where we're going to get it from and you'll see it all connect later how it's going to work so we're creating this function and the first thing we need to do is we need to let me put a comment and it's telling us generate a random token so a great package that we we can install which I think I already have installed on this application is uu ID version 4 package this will pretty much create a random string of characters so it's npmi uu ID V version 4 so we can go back to the code I could paste it here but I think it's already installed okay and now we have that package installed so let's import it at the top so we're going to import it above this function and let's create this random token so we could store it in a token variable and it is going to be uid Fe version 4 like that in invoking it next we want to make sure we Define the expires so to do this we're going to say new date and then we're going to get the time we're going to call the get time and then what we can do here is we can set an expires of when this token is not valid anymore so G up co-pilot is recommended in 24 hours so we're just going to go with that and you could change the hours based on the numbers here so say if you want 1 hour you could change this the one and then I could put this to one so this will be expires after 1 hour that's what it means right there okay so we have the token variable and the expires variable next thing we need to check is we need to check if the token check if a token let me see how I can we this check if a token already exists for the user perfect so sometimes a user might request a token request a verification token and then they come back a few minutes later they never redeem their token for SE or um verified it and they click it again so we want to make sure that we reset that token and pretty much send them a new one because it's going to cause problems if we don't send them a new one and they keep requesting a new one and they're going to wonder why the verification token process isn't working so this is just pretty much a safety precaution a in a sense so what we're going to call this is we're going to say existing token so if there's an existing token we're going to store it in this variable and we are going to await and then we're going to have to create a function which we are going to call get verification token by email and then we're just going to pass on the email and the reason why we're doing it by email is because that's what we're getting here inside of this whole function inside of this specific scope so we're going to get an error because we don't have this function right here made so let's actually create this function in a totally separate file we could create it inside of our data and what we can name this inside of our data folder is verification D token. TS and what we need to import here at the top is we need to import the database and the reason why is because we need to run some invoke and queries into our database using prism so we're going to create a function called get verification token by email which is perfect it's a synchronous it's accepting the email and what we're going to do here is we could do a try catch and inside of the try we could say cons verification token equals a wait database Dot and then we have that model verification token which we created in Step One do find first that's a method we can use and we have to do where there is email and we just put email or you could do email like that doesn't matter it's same thing and then what we can do here is after the wear and this function we can return the verification token just like that and then in this we could just do console.log and we could console log the error or whatever error checks you want to do there so now we are exporting this verification token by email what we can do here is make sure we import it at the top so as you can see we are importing it at the top now and we are good to go to the next step of this specific token so we are now checking if the token already exist by calling this database function and check in to see if there's a verification token in the system so next thing we want to do so we're going to say if there's an existing token so if there's an existing token what we need to do is we need to delete that token right so we need to await and then we have to use a database function again which we have to import at the top so I just did like that verification token. delete and we are deleting where the ID equals the existing token. ID so if you hover over like existing token you could see the field types that we have for the existing token and remember these are the field types we created in step one we have ID email token expires and ID is the unique identifier for the existing token so we need the unique identifier to delete the verification token if there's an existing token already so that means they keep click clicking requesting verification tokens within that hour time frame that's what this whole code means right here okay so if they get past that step next thing we need to do is we just need to create a new verification token right so that means they don't have a verification token or we deleted it for them so we could say we store it in a variable const verific ation token equals a weight database. verification token. create right we're creating a new one and we are going to create it we have to have a data object and what we can pass in there are obviously they have the ID which is unique we can't change that we have the email which we're getting we have the token which we created on line S and then we have the expired which we created on line8 and what we can do here is we could say it is a new date and expires then so we're just passing in that expires variable into this new date right here and we are storing it inside the expires in our database and after that all we have to do is say return verification token so that is US generating the verific token and now obviously it's not going to work because we haven't put it anywhere in our actual code so the most logical place if you had to guess before doing it is you have to actually put it inside of the register server action and the reason why is because when somebody registers we need to send them the generate verification token and you're probably wondering where should we put it where should we put it inside of that server action for register and the best answer to put that is pretty much at the end after all of your checks are done on the register like if you're hashing the password if you're making sure there's a user not related to the email that they're trying to register with all of those checks if they all pass and succeed then you should send the verification email so just think of it logically and it would make sense if you start thinking of it like that so what we're going to do is we are going to go after we create the user right and then look we're returning a success message of email verification was sent right next we are after we create the user we know it was successful ver uh register process we are going to generate a verification token right here and we can store this in a variable to verification token equals a weit and we created that function called generate verification token inside of our lip folder right so now we imported at the top and what we want to do here is we are just going to pass in the email like that perfect so that is generating the verification token and we can do a check on it before we move on to the next step to make sure we have nothing wrong so let's open up our terminal run the development server and while this is opening up make sure you guys don't forget to like And subscribe and let's go to the register page and let me open up my mongodb just to make sure I don't have a user related to any of these emails which is not a big deal we actually do that later so let's go to the register let's register with some random email so here Brett 1 2 3 4 5 6 1 2 3 4 five six we're going to click register and it says email verification was sent and that is only sent after pretty much all of the checks are made and we actually have no errors so our code should have rant and to check that we could go inside of our database so I like I said I'm using mongodb I do have videos on my channel explaining how to set a mongodb it's very simple very easy but I'm assuming you guys know how to do that if you're watching this video so what we're going to do is let's open up the right database and if it successful on the verification token it should have actually created a new verification token with our field types so if you look it says development verification token and as you can see this verification token was just created with that email so let me zoom in if I can so you see that email I just signed up with we have this random token that was generated with the uuid version four package you see here's the token and then we also have the expires as well with a unique identifier that mongodb creates so everything is working and step two is good so let's move on to step three okay so step three is going to be creating a function that actually sends the token through an email to the user that the email is pretty much provided by with the register form so we are going to go back first before actually going back in our code let's go to Google and type in resend email and send is essentially a modern way of sending emails through a react application so it is they do have a free version but it is limited when it comes to the free version and the way it's limited is you pretty much I don't know let me actually look at the pricing real quick so if we go [Music] to where is the pricing maybe homepage yeah pricing so as you can see the $0 month plane you do get at be able to connect one domain to resend pretty much this is a production domain that you can use or you can upgrade to the pro which is 20 bucks a month and you get 50,000 emails a month no daily sending limit and you could have unlimited domains so right now I am on the $20 month package because I do use it for other websites but you could sign up for free no credit card required and you could use the free plan and pretty pretty much essentially when you get onto resend let me just go back on so you get on to resend and there's another key point I want to mention too if you are use deploying using verell and you pretty much use that domain that's like for sale.app that doesn't count as a production domain that is actually ver selles domain so you can't use that as your domain so you do actually have to buy a legit domain like a.co doio whatever it is but you cannot use for sales domain so there is a way to get around sending emails if you don't have domain just to test out if you're just doing development work in the your local host and that is by going to their docs let me go to their docs real quick and let's go over how we can set this up so their docs are pretty straightforward and what we can do is we could do the nextjs quick start and the first package we should install is this resent pack package so let me do that first and then continue my thoughts of what I was doing I'm going to shut down my server install the resend package and we are going to go back to the documentation and then what you can do here is you can create an email template which we're not going to do um this is just an extra step it makes your emails pretty much look better which I'll actually have a different video on that of how you could use react email with resend to make your emails very very custom and very custom to your brand and the next pretty much step three is going to be to create an API file under your app- api-- route. TS so what we're going to do here is app API I think it was send and then a route .ts you could create it like that or there's actually another way to create it which we are going to do so you could do it through an API or you could just do it inside of your lip folder so let's delete this and we are going to go inside of our Li folder and we're going to go to new file and we're going to say mail. TS and inside of this is where we're going to pretty much create how our email is going to be sent so we're going to import that resend package that we did and this is going to be from resend like this and next thing we have to do is we have to initialize resend so we can do cons resend equals new resend and then you do parenthesis and you usually want to store this API key inside of your EnV file so I'm going to do process. EnV endore API uncore key just like that I'm going to copy this go to my EnV file paste it and then press equals and another thing that I forgot to mention which is pretty important is when you're doing next off or aujs you have to have this specific EnV variable named exactly like this next _ Secret and then it could be anything you could just put any random value you want and make sure like I said is underneath this name and you need to have this for next off the work so that is a good point thank God I went to the EnV file because if you don't do this you're going to run into errors and you're going to wonder what the error is so that is the issue right there is make sure you have a Seeker key for next off okay so let's go to resend real quick and what we need to do is we need to go to sign in so make sure you're signed into your account go to API Keys here at the left and you want to create an API key and I'm just going to do verification token tutorial full access and then you could just do all domains press add and you can only see this key once store it safely so make sure you copy it because after you close this you won't be you'll see the key again so I'm going to close the key and as you can see it's here on my dashboard and what you're going to do is you're going to copy that key and then just paste it inside of your EnV variable like this if we go back to the mail this is where it's being used inside of our mail okay another thing I want to do is I want to say cons domain and we're going to equal to local well http Local Host 3000 like this okay so that is just going to be our domain in variable that we stored as domain so now let's actually create the function we're going to name a send verification email this will be asynchronous function and what we are going to accept in here is we're going to accept the email which is a string and the token which is a string as well and you'll see why we're accepting those two so what we're going to do is we're going to create a confirmation link so we're going to name a confirmation link and we're going to use the template literal we're going to say domain so I did domain because when you go into production you could just change this to your production domain and it'll be easy to change and this is going to pretty much be a path of where we are going to send the user right so I'm going to name this domain slash we can name it verify email and then we are going to add a query to it and it's going to be the token and it is going to equal the token right and we don't want to have it equal the email because we only need the email to pretty much be able to send the email that's why we need email we need a know which email we're sending it to and this confirmation link is going to be essentially inside of the uh body of the email so you're going to click this confirmation link and go to localhost 3000 verify email and we are setting the query string of token equal to token so what we can do is we could use await resend. emails. send and you can find this in their docs on that page I was on and this is where we can use an email that resend allows us use so this is what I was talking about earlier and kind of cut myself off is if you don't have a production domain you must use this email so it's going to be onboarding at resend. comom let me just confirm it is and like I said if you do not use this email it's not going to work unless you do have a domain that's hooked up then use that domain so let me just make sure real quick okay so as you can see it says onboarding resend. deev so you could use this email make sure you use this email if you don't have production so it's going to be from onboarding there and the next one is going to be two and that is why we have the email so we're sending it to that email we have to define the subject which we could [Music] say verify your email and then the last thing we need is we could put this as HTML and what we can do in here is we can have a template literal and I'm just going to copy something over real quick to make this quicker it's going to be a simple P tag and what we're going to have in here is click with an a tag right and it is going to be the confirmation link so click here to reset to verify your email perfect and then make sure you have commas after everything so you don't have an error so that is us being able to send an email this whole function so we have to plug this function in because we're not using it right so we are also going to plug it in inside of the register server action so after all the checks and then we generate the verification token right we need to await the send verification email which is the function we just created and that is accepting email and is accepting the verification token. token and we're getting the token because we generated it here and as you can see hover over that and one of the fields inside of the object is a token and that's why it's written like that okay so let's go back to our mail and another key Point too is when you're testing in development whatever email you use to create an account so whatever account you're on you must send it to that email only obviously like I said if you have a production ready domain you could send it to any emails you want but you must send it to the email that's associated with your resent account that's the only way it's going to work so for me I'm going to make sure I have an account so I do have an account with email that have with resend so I'm going to make sure I register with this email so I'm just deleting from my database refreshing the page and we're going to test this out to see if I actually get an email it'll be nice if I could probably start the development server because that's the only way it's going to work and let's test to see if we are actually sending an email so we are opening Local Host 3000 let's go to the register page let's register an account with the email associated with your resent account we're going to click register email verification was sent so that means everything went smooth but to confirm we could do this again we could refresh the page and we should have two verification tokens in here because you remember the first one was the popular 11 domain at Yahoo and then the other one's my da Brett Westwood at gmail so we have this verification token and we should have been able to send it with resend so let me open up my email and as you can see 12:18 p.m. which it is right now it was sent zero minutes ago if you guys could see zero minutes ago we have a click here to verify your email from onboarding at end. and the subject line is verify email so the resend is working and we're actually sending an email and then if we click here that was that confirmation link we created with the domain variable so if we click let's look at the URL the URL is Local Host 3000 SL verify email with the query string of the token attached perfect so that is step three and now let's move on to step four so step four is essentially creating this page that we have not created yet and is going to be under this specific route here so we have to create a route for verify email obviously the rest is just the query string so let's go into our code inside of our app directory let's create a new folder called verify dmail let's just create this as a page. TSX and inside of here let's run the command rafc which creates a react functional component we just call this the verify email page and this page we want to make a client right but honestly what we can do is we create a component called verify email form and then we can make this client and let's create this in the components off or actually components new file verify email form. TSX rafc verify email form mark this as use client because we are going to have to use some client side hooks let's import this onto the actual page and let's go back to our code real quick and if we refresh the page you can see it's not a 404 not anymore it just says verify email form so we created the page and let's go to this verify email form and let's now actually work on the logic so the thing we need to do is we need to extract that token from the URL which we passed in as a query so to do that the hook that we have to use which is the main hook to make this whole thing work is called the use search prams and this allows us to read the parameters inside of the URL search another thing we can use is we can also use the use effect Hook and the use State hook as well and this is going to allow us pretty much just to run the command right when the page runs so the use effect and use search prams Hook is the main thing we need so inside of this div I am going to copy some stuff over because this is just UI and chatsi and stuff and just paste it in and it's just styling stuff and if you do want to see what it is you could go back look through the gith help repo and see exactly how this stuff was styled so we're just going to make sure we import all these components and then we are also using the use State hook because we got to store the success and all that inside of the successor error so let's do that contrl c so we're storing the state of the error success in the use State hook and then we have this beat loader which if there's an error which I don't even have the package for and I'm just going to put a ptag saying error instead or if there's no eror there's no that just put loading OHP wrong butt okay so we're going to do that and like I said we're going to use the use search prams so we're going to say cons search prams equals the use search prams and to get the token it's very simple we're just going to store it in a token variable and we're going to use the search prams dogit method and we are getting the token and the reason why it's token is because if you look at the URL it is token equals and then it's the token value and we put we're the ones who put token if you remember so if you go to your um mail inside of your lib you could see we put token here equals the token if we put with something else like token value equals token then you must get the token value from the use search prams but since we didn't do that all we need to put is token just like this and if you want you can console log the token which I'm pretty positive we're getting so I'm not going to console log it and that is how you get the token from the URL next thing I want to do is I want to create a use effect and the reason why we're doing this use effect is because we need to see if this token is verified right when the page loads so right when the page mounts we want to see and what we are going to do here it's not going to be token is we are going to have inside the use effect so here's our use effect we're going to call the onsubmit function you can name this whatever you want we're just going to name it onsubmit and the onsubmit function is going to fire right when the page pretty much bounced so let's create this cons on submit is going to be an asynchronous function or actually it's not going to be an asynchronous function my fa guys we are going to use the use call back function and this is coming from react just like that so we're going to say cons onsubmit use call back right we're going to do it into an arrow function and then let's do some checks so we're going to say if there is a success or error we're just going to return and the reason why we're getting this error is because we haven't done the mount like the dependency array at the end like that so now it's no error on the use call back so if there is a success or error we're just going to return another thing is we're going to check if there's no token so if there's no token which I mean there could be no token sometimes it could run into an error we're just going to set the error to no token provided and return the function and then those are pretty much all of our checks so the next thing we have to do is we actually have to code the logic so we're going to create a thing called new verification token like this or no new verification and we are going to pass them the token and what this is is we had to create this as a server action so we do have our folder at the top called actions so if we look here and what we can do is we can just pretty much create a new file called new verification. TS oh noty and now we can actually write the logic of us checking the verification token when they land on this page after clicking the link from the email so first thing is inside this use server we need to mark it as a use server next I want to import the database so we could do some queries from the database we also have a function inside of my data folder which I recreated which was called get user by email and I just want to show you that real quick pretty much it's just us getting the user from our database by providing the email and searching for it using email okay so we have that import at the top and then we also are going to import the git verification token and we actually have to create this one so we're going to say get verif ification token by token right and this is going to be we could actually create this one inside of our data folder too so inside the verification token file inside of your data folder we are going to create this function so we're just going to get it cons get verification token by token it is going to be asynchronous accepting the token as a string and GitHub co-pilots pretty much dead on we are just doing a TR catch block and we are doing a database invion inside of the verification token model we are finding where the token is the token and just returning that verification token and let me just give rid of this error by oh we haven't exported yet yes so we haven't exported yet so we're not going to be able to get rid of that error and let's do export cons new verific a this will be an asynchronous value it is going to accept the token which we're passing in and it's a string and what we're going to do is we're going to see if there is an existing token so first thing first let's see if there's actually a token there so this is a check so get verification token by token and passing in that token that's the function we just created okay so next we're going to say if there's no existing token we just say return error invalid token and we are storing the error and the success and the state on the front end so it should display if there is a success or error message so that's why we're writing exactly like that we're also going to see if the token has expired so we're going to say equals new date and we're going to get the existing token. token or not. token dopes and if that is less than the new date then that means it has expired okay so we're going to say if it has expired we're just going to return an error saying token has expired perfect so now we just need to make sure we have an existing user so we're going to wait get user by email and we're going to use the existing token. email okay and we're just going to say if there's no existing user return an error Sy user not found okay now here's the good part so now we can actually update our database in our user so we're going to say database do user. update and what we're going to update is where the ID is the existing user. ID like that and what we have to do here comma and we are updating it and what we're going to update is email verified so where we're getting this from is on step one inside the schema. prism we added on line 20 the email verified with the day and time so we're updating that because right now it's technically null because it is optional so it just becomes null or undefined depending on how you defined it so what we're going to do here is we're going to say new date so whenever this function fires it's just going to give it the new date of whatever time and date it is at the moment and then just email we're going to do the existing token. email just to make sure everything looks good yep everything looks good and then let's run one more database query where we're going to go inside the database. verification token and we're going to delete that token and then if everything looks good we can just return a success message saying email verified just like that let's go back into our page we could import This Server action now and as you can see the server action is imported and now we can finish pretty much the functionality of the code on the front end right so let me get to that real quick so what we could do here is we could do a do then and then we could just pass this in as data the data if it's successful we're just going to do it data so if data. success so if it's success let's set that success message to data. success and then we're just going to put if data. error let's set the error to the data. error okay and let's do a do catch just in case and what we can do here is we can console log the error and set the error to an unexpected error has occurred and we could just pass in the token inside of the dependency array we could also pass in success and error as well inside of this use callback array here so what this page is doing again is you land on the page right when it amounts this onsubmit function is called which is here it calls it does a few checks runs that server action with the new verification token and if it's successful it's going to set it to successful and in the server action it essentially updates your email verify to the specific date that function was ran on so that means your email was verified and it just sends you a success message pretty much saying that now you're able to log in so that is Step number four so let's go to step five to actually be able to let us log in if the email is verified or not so OJs version five even version four allows us to use asynchronous callbacks and these are very powerful callback functions that run when a specific event is fired or something happen happens so we go inside of our um alt. TS file right we can actually create an asynchronous callback to allow the user to log in or not based on certain criteria or parameters right so what we can do is there's an asynchronous call back called the sign in call back so right above the session one I just have here we're just going to have the sign in and and what we're going to pass into it is going to be the user and the account and the account is pretty much just if there is a Google provider or not or GitHub whatever you're using and the user is the credentials provider I'm just have an account here because a lot of people do use their Google provider and this logic is going to be good if you do have the Googles or GitHub or Facebook provider so just follow along with this so what we're going to do is if the account so if the account oh man I can't even spell provider does not equal I still can't spell if the account. provider does not equal their credentials right so if it's everything else it could be anything else let's just return true so how this call back works is if it returns true it allows you to sign in and if you return false it doesn't allow you to sign in So at the very end it should return true that's why we're still getting an error perfect so we're doing this one check if the provider is not the credentials return true that means if it's the Google provider it's already a verified email let them log in so next we are going to do look for the existing user right so we're going to do a wait get user by ID and we're going to pass in the user. ID and what it's saying is it's of argument type string or undefined so what we can do here is just fix that type error like that so we're getting the existing user which is the ID name email email verified or password and as you can see email verified it could either be date or null so what we're going to do is we're going to say if there is no existing user. email verified right if there's no email verified so that means it's if if it's null we're just going to return false they're not allowed to log in so this pretty much five to six lines of code right here is the logic of if they could log in or not depending if their email is verified or not so let's test this out right so obviously this says invalid token let's start from the beginning and try everything out from the start so I'm going to delete the user delete the verification token and delete the user okay so we are going to log in I mean not log in we're going to register email verification was sent so I'm not even going to verify my email I'm just going to try to log in because Yello right some people just try to log in they don't think it's going to work like they think they can still log in so we're going to do the same email and we're going to try to log in please confirm your email address as you can see that is an error message I sent to the backend if we get the specific error of return false so we have to confirm the email address and let me see where I put that specific error which please confirm so it's inside the login action so if you go inside the login action I have a try catch here at the bottom and and if the error is instance of au there and if the error. type is a credential sign in we're going to return this error other than that default we're going to have an error please confirm your email address so this is inside of the login server action that is why we're getting this please confirm your email address so let's go and confirm the email address right so verify email the one that was just sent a minute ago we're going to click we're on the page it loaded it did the use effect when it mounted and we got success message saying email verified right so now let's go back to our login page which that's not even the login page is just slash login or slash signup I made it I made a SL signup or sign in and now let's try to log in and as you can see I am red directed to the dashboard and I am logged in I probably should console log this session let me do that real quick to show you that I'm actually logged in but that is essentially how you do the verification token and how you can create it and pretty much make sure that they are have access to that email but let me just make sure that I am logged in so let's go to our dashboard page which we don't even have have created so let's create a new folder called dashboard page. TSX ra fce we're going to import Au right and this is coming from at SLO and it might be wrapped in a curly brace which it is okay cool so what we can do is cons session equals 08 off like this and this could be asynchronous and what we can do here is we could say Hi and then session dot user dot email so let's go to our dashboard page and see if it says that so as you could see it does say Hi and then my email so we are logged in and we can access the session through that o object that is on the o TS file when we configured it at the very beginning of the video okay guys so I know this was a long video so thank you guys for watching if you did stay through the whole video but other than that if you did like the video hit that like button and also subscribe if you want content very similar to this it does motivate motivate me when you guys do hit that like button subscribe as well and like I said if you guys do have any questions leave them in the comments section or join our Discord room which we can answer a bunch of questions related nextjs OJs react anything JavaScript related to as well we'll be able to answer we have a group of about 300 people in there right now so it'll be nice to have more people join but other than that thank you guys for watching till the end everything will be timestamped and hope you guys have a great day
Info
Channel: Brett Westwood - Software Engineer
Views: 600
Rating: undefined out of 5
Keywords: verification email with authjs, verify email with nextjs, how to verify email when user registers, email verification with resend, nextauth, next.js tutorial, nextjs tutorial, next auth credentials, authjs credentials, next auth typescript, send a token to verify email, how to generate a verification token, verification token in next auth, nextjs 14 tutorial
Id: QyGJLm55EDk
Channel Id: undefined
Length: 59min 1sec (3541 seconds)
Published: Thu Apr 18 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.