NextAuth Credentials Provider Integration | Next.js App router

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey welcome back to my Channel today we're going to learn how to add NEX off into an app router project now the example we'll be using in today's video comes directly from the next learn course which I will link in the description below it's completely free so if you want to go into more detail or you prefer written content I recommend checking that out today's video covers chapter 15 otherwise let's just open up our text editor and jump right into things all right so we already have the UI of our login page put together as you can see here but if we test it out you'll see it has no functionality so let's add this authentication functionality using next off okay so let's dive into authentication it's not just about signing in and out it involves a whole lot more like managing sessions and handling various authentication aspects sure we could implement this from scratch ourselves but it's Error prone and timec consuming and honestly there's no point in Reinventing the wheel when we have NEX o at our disposal NEX o offers a very straightforward and cohesive solution for handling authentication in nextjs apps it abstracts away the complexity involved in managing sessions signin sign out and other aspects of authenication so let's start off by setting up next off in our project first we can install it by running the following command in our terminal next we need to generate a secret key that will be used to encrypt cookies ensuring the security of our sessions so to do this just run the following command in your terminal and you can see it generates a random string of 32 bytes and encodes it in Bas 64 format now we need to add the environment variable oore secret to our EnV file using the secret key that we just generated as the value like this okay now at the root of our project we need to create an O.C config.txt an O config object this object will contain the configuration options for next o for now it will only contain the pages option this Pages option can be used to specify the route for custom signin sign out in error Pages it's not required but by adding the signin key with our login path into the pages option the user will be redirected to our custom login page rather than the default login page provided by nexo next we add a new Option called call back and we'll add this code within it like this here the authorized callback is used to verify if the request is authorized to access the page via next middleware it's called before request is complete and it receives an object with the off and request properties the off property contains the user session and the request property contains the incoming request we'll also add the providers option which is an array where you list different login options for now we'll leave it empty we'll revisit this later but it's necessary to satisfy the next off config okay next we need to import the off config object into a middleware file so in the root of our project let's create a file called middleware TTS and paste in the following code here we're initializing next o with the O config object and exporting the off property we're also using the match option from middleware to specify that it should run on specific paths by using middleware the protected routes will not even start to render until middleware verifies the authentication which enhances both the security and the performance of our app okay so in this app we're going to authenticate using the credentials provider this means the user will log in using a username and a password as opposed to say their Google or GitHub accounts when working with passwords it's good practice to Hash passwords before storing them in a database hashing converts a password into a fix length string of characters which appears random providing a layer of Security even if the user's data is exposed in this application a package called bcrypt was used to Hash the user's password before storing it in our database we'll be using this package again to compare that the password entered by the user matches the one in the database so make sure this is installed by running the following command in your terminal now we'll need to create a separate file to use the bcrypt package this is because bcrypt relies on no. JS apis that are not available within our middleware so let's create a new file called off. Ts that spreads our off config object like this now we need to add the providers option for NEX off providers as we kind of mentioned before is an array where we can list different login options such as Google or GitHub but as as I already mentioned in this video we will be focusing on using the credentials provider which again allows us to log in with a username and password all right now we can add the sign in functionality we can use the authorized function to handle the authentication logic we'll use Zod to validate the email and password before checking if the user exists in the database so make sure it's installed by running this command in our terminal and now let's import it and use it like this after validating the the credentials we'll create a new G user function that queries the user from the database so let's import our database and user types like this and add this code to create our get user function now in our authorized function we'll use this function to check if the user exists in our database then we can import bcrypt and call bt. compare to check if the passwords match like this if the password's match we want to return the user otherwise return null to prevent the user from loog in now we need to connect the off logic with the login form and our actions. TS file will create a new action called authenticate this action should import the signin function from off. TS and it will look like this here we attempt to sign in a user using the signin function from next off with the provided form data and if there's a credential signin error we show the appropriate error message finally let's move into our login form component we can use reacts use form state to call the server action and handle form errors so let's import use form State and our authenticate action and we'll use it like this now we can use dispatch to trigger our authenticate server action so let's add this to our form and then down here in our Forum we can use error message to display any errors like this finally we can use use form status to handle the pending state of the form so let's import it and then down in our logic button we can get pending from the use form status hook pending represents the current status of the form submission specifically indicating whether the form submission is in progress when pending is true it implies that the form is currently being processed so now we can use it to disable the button until the form submission is complete okay now let's test this out so here we have our app running locally and first let's enter the wrong credentials notice our error message displays correctly now let's try to manually update the URL to take us to the dashboard without logging in you'll see we get directed right back to the login page this is because of our middleware matcher finally let's enter the correct credentials and here we have it we have successfully logged in now all that's left to do is add the logout functionality so here you'll see we have a sign out button but if we click it it doesn't actually sign us out with next off adding this functionality is extremely simple let's move into our side naav component where we have our sign out button and here all we need to do is call the sign out function from o. TS in the form element so let's import sign out from o and call it in our form like this now if we go back to our browser and test it out we'll see that our logout functionality works and that's it our implementation of authentication is complete all right thanks for watching I hope you enjoyed it as usual if you have any questions feel free to leave them in the comments below otherwise I hope to see you in the next video bye
Info
Channel: this.stephie
Views: 11,929
Rating: undefined out of 5
Keywords: next.js, NextAuth, AppRouter
Id: splh0ZIo-s4
Channel Id: undefined
Length: 7min 54sec (474 seconds)
Published: Fri Dec 08 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.