Auth.js V5 From Scratch

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
arjs version 5 has some breaking changes that might make you confused but don't worry in this tutorial I'm going to show you how you can set up arjs version 5 with the nextjs version 14 project from scratch first I will configure the next o version 5 with Google provider as well as the credentials provider and then I'm going to show you how you can protect your client component Pages as well as the server component pages and lastly I'm going to show you how you can protect your pages with next AR version 5 middleware welcome to sacur Channel and without further Ado let's get right into it okay I open up a brand new nexj version 14 project and here in the first step we need to install the next off version five so I open up the terminal okay and here I'm going to say npm install next off AD Sign beta okay this will install the next off version five for us okay it is installed and in the next next step we need to create an .ts file in the root path of our project so I close the terminal Here and Now inside the root path of our project I'm going to create a file called off. TS actually the name of this file is up to you and here in the first step we need to import type next off config from the next o and then here I'm going to create a config object so here I'm going to say cons config and then set it to an object and say that it satisfi the next o config type and then inside the object I'm going to specify the providers here okay so providers as you may know are the specific ways of the authentication in the next app for example you can configure Google provider in which users can sign in into your application with their Google account or GitHub or Twitter and so on and also you can configure the credentials provider in which users can sign in into your application with their own username and password so in this tutorial I'm going to configure the Google provider as well as the credentials provider [Music] here so the first one is the Google provider so we need to import the Google Provider from the next off/ providers SLG gooogle and we name it Google here and then here we can pass it inside the providers list okay and here in the version five we don't need to pass the Google client ID and Google client secret directly inside the Google provider we can create an EnV file here so in the root path of our application I'm going to create a EnV file env. local okay and then inside this file we can put our Google client secret and Google client ID and the next off version five automatically inferred them from the EnV file providing that they are started with the a prefix so as you can see here the EnV variable should start with the a prefix in the uppercase they underscore the name of the provider again it should be in the uppercase and then underscore ID or secret so if you name your EnV variable with this pattern the next AR version five automatically infert their values and configure your provider so in our case we are going to use the Google provider so here name of the en variable should be something like this off and then underscore Google name of the provider okay and then underscore ID and also _ Google secret okay so we need to put these two EnV variable inside the env. loal file so let's copy the first one and go to the vs code and that env. looc file and put it here okay and put the second one which is _ goore Secret okay now we need to go to the Google APR console and create a project and from the project get the value of the Google ID and Google [Music] secret so I go to the Google API console okay here I'm going to click on the create project here we need to name the project then name it Sakura Dev tutorial okay and then click on the create here and waiting for the project to be created okay and then click on the select project here and then here I'm going to click on the API and services first we need to click on the oo consent screen and configure the consent screen here we're going to click on the external here okay and then click on create we can put the name of the app I'm going to go ahead with the Sakura Dev tutorial again yeah okay put the user support email and also here put the develop veler email address I'm going to go ahead with the same email address and click on the save and continue and again click on the save and continue and again save and continue okay now we can back to the dashboard okay and then click on the publish app it's very important you should click on the publish app otherwise you can't use this service here okay so I click on the confirm here and then in the next step I'm going to go to the credentials here okay and then click on the create cred ials I'm going to select the O client ID and here in the application type I'm going to select the web application and on the name of the application again I'm going to go ahead with the Sakura Dev tutorial okay and here we need to click on the authorizer direct Uris and here in the authorizer direct uis since we are using Google provider we need to put the uis something like this if we are in the production mode we put the htps and then your domain and then SL API SL off SL callback and then slash Google but since our next year's project is now on the development environment we need to put something like this HTTP and then SL SL Local Host 3000 the address of our def server and then SL API SL off SL callback and then SLG Google so let's copy this URI and get back to the Google API console and put it here in the authorized direct uis okay so after the authentication with the Google provider is successful the Google API will call this API from our application and send the user information to this API so we need to put it here exactly like this/ API slof and then SL callback SLG gooogle okay so now let's click on the create here and now we can copy the client ID and go to the vs code and here in the O Google ID I'm going to paste the Google client ID that we've got from the Google API console and let's get back to the browser and copy the client secret here okay and get back to the vs code and paste it here in front of the O Google secret okay so that's it for the configuring the Google provider let's close the EnV file and get back to the off. TS as you can see we just need to send the Google provider inside the provider list of the next off config object that's it the next off version five will infert Google client ID and Google client secret from the EnV file that we've just created okay we just need to follow the naming convention that I've just mentioned okay so now let's move on and now here we can export the handlers from this file so here I'm going to say export const and object and let's set the object to the next off function that comes from the next off okay as you can see it is imported from the next off and and we just need to pass the config object that we have created earlier okay so going to pass it to the next OD function and now here we can D structure the Handler also the off which is very important function and is one of the breaking changes that is offered by the next out version five okay and then structure the sign in function and also the sign out function and now here we need to create a catch all API rat Handler for the next stop okay so as you might notice here in the version five we have separated the configurations object from the next off Catal route and put it inside the off. TS file in the root path of our application so now let's go to the app directory and create the API routes for the next off so I'm going to create the API directory and then off okay it should be SL API SL off and then the catch all route of the next off in inside the square brackets I'm going to put three dots here and then next off it should be next off so pay attention to the spelling here and then inside this directory I'm going to create the route Handler route. ts5 okay so this will be the catch all API R of the next off first we need to import the handlers from the off file that we have just exported from okay you can see here we export the handlers from the off. TS file and here in the next off catch route we need to Port the handers okay as you can see is a really long path for the off file so let's go to the TS config thejason file and here let's create a Alias path for the off. TS file so here I'm going to say off okay it's an alias for the off. TS file and it will be on SL off. TS file okay so let's save this and now we can go to the next off Catal routes and just replace this path which is off and now in this file we just need to export the get and post function from the Handler's object so here I'm going to say export con distraction object and set it to handlers okay and extract the get and post from the handers object that's it for the right Handler of the next top as you can see it is much simpler than the version four in the version four we needed to put the configuration that we have put inside the off. TS file here into this route Handler but in the version five just need to export the get and post from the handlers that we exported from the .ts file we separate the configurations and put them inside the .ts file okay so now let's see how we can use the next off in order to protect our application from unauthenticated [Music] users so first we need to create an app or for our application and then we will put the sign in and sign up button in the app bar of our application so in the app directory I'm going to create a new file called app. DSX okay and here inside it let's create an react component okay and then here in the root div our appar let's put some class name here I'm going to put some padding here and a gradient background okay so inside this div I'm going to create another div here and in the class name I'm going to use the mlr for pushing this div all the way to the right of the app bar okay so as you can see here we have the flex inside the parent div and the margin left Auto will send this div all the way to the right of the appar okay so inside this div here we need to check if the user is authenticated put the name of the user and a sign up button and if the user is not authenticated just put a sign in button so first we need to check if the user is authenticated or not how we can do that that we can check it with the off function so first let's make this upper component async component so now it's a async server component and then here inside the Apper we can retrieve the session of the next o with the AR function so here I'm going say const session and then set it to await and the O function that comes from the o. ts5 so let's get back to the a. TS file you can see we have exported the a function from the a.s file so back to the app part. TSX here as you can see we have retrieved the session of the next off with the off function okay now here inside this de we can check if the session is existed and session has a user inside it okay we can render a deep here okay and then inside the first deep we're going to put the username so I render a P tag here okay and here I'm render session. user.name okay and then here after that we're going to render a sign out button so since this is a server component we can't use a button with the unclick event so in order to avoid making this component a client component we're going to render form here and then a submit button inside it and then set the action events of the form element so in this way we can keep the appar component a server component okay so let's create form here and here let's create button okay so let's format this jsx now inside the form here let's create button and let's set the caption to sign out okay and let's set the type of the button to submit okay and now inside the formul M we can set the action events we can put a function here it should be an async okay and then inside it first want to mark it with the use server so now it's a server action and then we can await the sign out function that comes from the O file okay so as you remember we have exported the sign out function from the OD file let's save this and if the session is not existed or the user is not existed inside the session it means that the user is not authenticated so in this way here we need to render a signin button so here in the second case which the user is unauthenticated again render form here and inside it we going to render a button again and set its type to submit okay and let's set the caption to sign in and then here we set the action event to an Asing function okay so we do that because we don't want to make this component to a client component we're going to keep it as a server component so we need to set the action event with a server action so again let's mark this function with you server okay and then await the sign in function that comes from the O file okay so let's save this and now this will be a part of our component and now let's go to the root layout of our application and here B the children of the root layout we're going to put the app bar that we've just created okay let's save this and now let's run the application with npm run def let's open it up in our browser okay so let's go to the browser you can see we have the app bar here and there is a sign in button here so if I click on the sign in here it will send us to the default signing of the next do which will be created by the next do itself we can also have a custom signin page we have I think two or three video about how we can create a custom signin page for the next a you can watch these videos if you want the procedure is the same with the next off version for so here if I click on this sign in with Google here you can see we have a configuration error so that's because we didn't create the off secret variable inside our local EnV file so let's get back to the vs code here okay let's close off the terminal and inside the that env. local file we need to create another variable prefix with the uppercase of and then underscore secret okay so this will be the secret key of the next Al and with this secret key next off can turn the session of the next off into a JWT and keep it inside the server so let's put a random string here if you are on a Linux machine you can use the open SSL to create a random secret key for the a secret so let's save this okay so now let's open up the terminal and restart the server okay and click on the sign in here sign in with Google and you can see see now we can go to the sakra tutorials I'm choose one of the email address here okay and for the first one I click on the continue here now we can see the name of the user here inside the Apper and then aign out button so now let's get back to the Apper components okay let's close the terminal and go to the Apper components here inside the first where we render the name of the user let's put a class name here and add a flex class and GAP two let's save this and get back to the browser we can see now the name of the user here and a sign out button so if I click on the sign out you can see the name of the user is now gone and instead a sign in button is shown in the appar so again let's click on the sign in with Google let's choose the account and again we can see my name here and the sign out button so in this way we can log in into the application with the Google provider of the next [Music] off now let's configure the credentials provider in the next o version five okay so let's go to the A.T file and here inside this file first we need to import the credentials Provider from the next app SL providers SL credential okay and then here before the config object I'm going to create another config object and name it credentials config so here I'm going to say const credentials config okay and set it to credentials provider that we have just imported from the next off providers and then passing configuration object here into the credentials provider function so here the first property we're going to set is the name we're going to set it to credentials okay and the next one is to create the credentials object so here I'm going to specify the credentials object and set it to an object here so what is this credentials object it has two main purposes the first one is to define the shape of our credential for example we want to say that our users must have the username and password in order to be able to sign in with the credentials provider you might want to specify the email and password as the credentials of your user but I'm going to go ahead with the username and password so the first purpose of this credentials object it defines the credentials properties it has the username and password inside okay and the second purpose of this credentials object is that you can specify the type and the shape of the inputs inside the sign in page of the next off so here in this object we can specify the label the type and other properties of the inputs inside the sign in page for the credentials provider so the first property is the user name again the name is up to you you can set it to email for example or whatever you want okay now we can specify the properties of the username input inside the next off signing page so here we can specify the label and set it to usern name okay so now the label of the username input inside the signing page is the user name and then we're going to specify the password okay and now inside the password object we can specify the label for the password can set it to the password okay and also we can specify the type of the input and and they're going to say it is a password type input okay so now this is for the credentials object and next we're going to define the authorized function inside the credentials config so here after the credentials object I'm going to Define Asing function authorize okay and it gets the credentials as its parameter okay so the type of this credentials will be inferred from the credentials object it has the username and password inside it okay now now we're going to define the body of the authorized function so what is this authorized function when the user click on the sign in button in the signin page the username and password will be packed as a credentials object and will be sent to this authorized function and in this authorized function we need to decide whether username and password is correct or not if these credentials are correct we need to return an user object associated with the username and password that user provided in this sign page and if the credentials are not correct we can just return null from this authorized function and returning null from this authorized function means that the user is not authenticated or authentication has failed so we need to decide if the credentials are correct or not in the real world scenarios where we have a a separate backend server we need to call the login API of the backend server and send the credentials to it and wait for the response the back end gets the credentials and checks in inside its database whether such a user is existed or not and if that's the case it will return the user object and then we can return it from this authorized function if we use the nexj as a full stack project usually we have a database and we can access it inside the NEX CH with some orms like Prisma or drizzle orm so here in this authorized function we're going to check inside our database if such a user is existed or not but here in this tutorial in order to keep it simple you don't want to create a database with Prisma or jel orm just naively check the username password with some hardcoded predefined username password so here we can say if credentials. username equals to for example SK are predefined hardcoded user and its password credentials. password equals to for example 1 2 3 you can allow user to sign in into our application so we just return a user object here okay and set its name to my name okay and else we just return no from this authorized function so we're going to keep it simple you can watch my previous videos I have completely explained the authorized function with the real world scenario I have configured the Prisma database and check inside the database whether the user is existed or not and then check the provided password with the hashed version of the password inside our database with the bigr library but here let's go with this simple authorized function okay so now we can put this credentials config object into the providers of the next off so here in the config object here we can add the credentials config here and now let's go to the browser let's sign out first then if I click on the sign in you can see our signin page has a sign in with credentials option inside it and we can sign in into our application either with our Google account account or with our username password so first let's go ahead with some wrong username password skk for example a wrong username and click on the sign in and you can see the sign in is failed message so now let's go ahead with the right username and password okay and click on the sign in credentials you can see my name here in the app part of our application so in this way we can configure credentials provider and allow the users to sign in into our application with a username and [Music] password okay so in this section I'm going to show you how you can protect your pages with the next off version five first I'm going to show you how you can protect your client component page and then in the next section I'm going to show you how you can protect your server component pages and in the last section I'm going to show you how you can use middle work to protect any page you want with East so now let's create a client component page and then protect it from unauthenticated user with next off version five okay so here I'm going to go to the app directory and here I want to create a new page and I'm going to name it client page okay and then inside it we're going to create a page. TSX file let's create a component here inside it we can say this is a client page and must be protected okay and now let's go to the upper and here let's create a link for this page I'm going to use the next link here okay want going to set the caption to client page okay and then set the edre to slash client page okay and let's get back to the browser you can see the client page here and I'm going to click on the client page you can see this is a client page and must be protected so if I sign out here and then get back back to the homepage and click on the client page you can see even though we are signed out we still can access to the client page so here let's protect this page from unauthenticated user so I go to the vs code and here inside the client page we're going to use the use session hook in order to access to the session of the next off inclin component so here I'm going to say const for now an object and set it to use session hook that comes from the next off/ react okay and then here from the object we're going to rename the data to the session so now we can access to the session of the next St and since we are using the use session hook we need to mark it with the use client directive okay and here we can check if session is not existed or session is existed but there is not user inside it so session that user is not existed we can just return a custom map message for example div here and say you need to sign in okay let's put some class name here text red 500 and a padding P example five okay so let's save this and this will not work so let's see we have an error and that's because in order to access to the use session hook we need to wrap our application with the session provider so as you might know the use session hook it's just a react context API so we need to wrap the application with the session provider and then we will be able to access to the use session H so let's go to the vs code and in the app directory let's create a providers component okay and then here let's create a component providers okay and these providers must take their children as its props so here let's have the children and let's set its type to type here it has the children which is going to be a react note okay and here let's remove this div here and change it to a session provider which comes from the next off SL react and then inside it we're going to render it children okay and here we need to mark it with the use client so it's a client component okay and now let's go to the rootlet of our application and here let's wrap all the pages and component of the application with the providers component that we have just created okay so now we can access to the use session hog inside any client component page that we want and here notice that this providers component is a client component and you might ask wrapping all the children of our application inside the client components providers doesn't make all application to a client components and the answer is no we still can have several components in our application wrapped by a client component so for more information about this you can watch this video but here I want to say that this will not make the whole application to a client component we can still have our server component as you will see in the next section so now let's go back to the browser okay you can see here in the client page we are not signed in and you can see this message here you need to sign in and the main content of the page is not shown to user so if I click on the signing and provide our username and password now we can see the main content of the page is now shown to the user because we are signed in into our application so in this way we can protect the client component pages from the unauthenticated [Music] user now let's create a server component page and see how we can protect from the unauthenticated user so let's get back to the vs code and here inside the app directory I'm going to create another page server page and inside it we're going to create page. TSX file okay and here let's create a component and here in the main div I'm going to say this is a server page and must be protected okay so this is a server component and we can't use the use session hog to retrieve this s instead we're going to use the O function from the O file so here first we need to turn it to an Asing component okay and say con session and set it to wait off okay the off is coming from the O file and in this way we can access to the session of the next up server side no need to the get server session from the version 4 and no need to pass any off option inside it and I think that is easier in the version five to access to the session in the server s side okay so now let's get to the client page the rest is the same let's copy this from the client page and here let's paste it inside the server page okay so as you can see if this session is not existed or there is not user inside this session we can return a div let's say you need to sign in okay so now let's save this and let's go to the appar and put a link for This Server page okay name it to server page and set it address to slash server page okay let's save this and now let's go to the browser first let's sign out let's go to the server page I think I misspelled the address of the page so let's get back to the res code here we have the oh we missell the server page here let's put the r here server page let's get back to the browser you can see now we are in the server page and the message is you need to sign in in the server page so if I click on the sign in okay put the username and password you can see now this is a server page and must be protected this is the main content of the page and is shown to the user because we are signed in into our application so in this way we can easily protect our sever component pages from an authenticated [Music] user okay now let's protect our pages with next off middleware so now let's go to the vs code and here inside the app directory I'm going to create a page for testing the metalware I'm name it metalware protected okay and then inside it I'm going to create the page. TSX okay let's create a page here and inside the main div let's say this page is protected by middleware okay let's save this and now let's go to the upper and here let's create a link for this middleware page I'm going to set the caption to middleware protected page and set the hft the/ middleware protected let's save this and here inside the root path of our application let's create a middleware file middleware TS okay and here let's export the O as middle work and this AR is from the AR file okay so we just export the AR as the middle in this file let's save this and then we need to go to the off file and here inside the config object we need to specify the callbacks object here and inside it we need to define the authorized function okay it takes the request and out as its parameter it's a little different from the middleware in the version four so here we need to specify on which path we want to use the middle word okay so here inside the body of the authorized function first we need to extract the path name from the URL of the request so here I'm say const and here put an object here and set it to request. next URL okay and then we can extract the path name and here we can say if the path name equals to slash middleware protected we can turn the off to a Boolean and return it from the authorized function so we just put two exclamation mark to turn the a to a bullion otherwise we just return true okay so in this way we are saying that if the path name equals to Middle protected route we turn the off to a Boolean and return it from this authoriz function the type of the O is the session so if the session is existed the O will be true and if it's not which means that the user is not authenticated the AR will be turned to false value and returned as a false value from this authorized function so again first we check if the path name is middleware protected which means that the middleware should be enforced with this path we just check if the session is existed we return through otherwise we return false and if the path is not middleware protected which means that we don't need to protect the page which is return true and allow user to go ahead and access the page because this is not a prot Ed page so I hope you guys get the idea if you have any question about that you can ask me in the comment section below so now let's go to the browser you can see we are not signed in here and if I click on the middle World protected page you can see we are headed to the signning page automatically so let's log in into our application you can see now the protected Page by middleware is now shown to the user because we are signed in so if I signed out and then want to go to the middle of protected page you can see we are headed to the signin page automatically so in this way we can protect our Pages without needing to do extra work inside our Pages we just need to specify the path name of the pages inside the authorized function okay so that will brings us to the end of this video and in the next video I'm going to show you how we can upgrade a full fled project with next a version 4 to the next AR version five so if you have haven't subscribed to my channel make sure to subscribe to the channel and hit the like button because it will give me more energy to move forward have a nice time stay tuned for my next video bye-bye
Info
Channel: Sakura Dev
Views: 18,402
Rating: undefined out of 5
Keywords: nextauth, nextauth v5, next-auth, nextauthv5, nextauthjs, nextjs authentication with nextauth, auth.js v5, nextauth js, auth.js, next-auth v5, nextauth.js v5, next-auth v5 + next js 14, authentication with next-auth, next auth v5, authjs, nextjs14 auth with nextauth, nextjs 14 auth v5, nextauth js tutorial, nextauth nextjs 13, nextauth tutorial, nextauth with nextjs14, nextauth user authorization, next.js 14 authentication with nextauth, nextauth features
Id: Rs8018RO5YQ
Channel Id: undefined
Length: 36min 40sec (2200 seconds)
Published: Mon Feb 12 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.