Next Auth Basics tutorial | Add Google, GitHub, Twitter, and Email authentication in Next.js project

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's up guys how's it going welcome to the next auth complete guide in today's video you're going to learn how to add user authentication system with providers like github twitter and google in your next year's project in the previous video series we have learned how to create a jam stack blogging website with nexus you can check that out if you want i'll put the link on the description so in that application we have added many features like embedded components then view counter auto completion search and so many other things but we didn't add any user authentication system so in today's video we're gonna add just that we're going to add user authentication system with next auth it is a library which will allows you to create authentication system for your next year's project so in this video we're going to build this we're not going to make any useful application my goal is to teach you how to add authentication system with next stop after watching this video you can implement the authentication system on your application so basically this is our sign-in page we have these three buttons for signing in with github twitter and google so let me give you a demo i will log in with google so click on this button and now it is asking me for choosing an account so i'm gonna choose this one and it is saying checking authentication you are already signed in and i'm redirected to the home page and it says sign in as my email address and it also has a sign out button so let's click on it and again now i'm in the sign-in page so you can see that google authentication works we will also add email authentication system then we're going to learn how to set up a database where you can store user data i'm going to use mongodb as our database but you can choose whatever you want and all of this authentication logic will be written in a single file because netgear simplifies everything for us so if you are interested about today's video please consider like this video and subscribe to my channel to see more of this react.js videos so without further ado let's get started let me give you a quick introduction of mine my name is sanjon i'm a full stack web developer who can develop complex web application from ui to backend systems you can watch my work by visiting my portfolio website that on john dot me then just go to projects and here you will see all of the projects that i have worked on i'm looking for a new opportunity in a company where i can provide great value with my skills and knowledge so if you are a recruiter or someone who wants a new team member who can solve problems can develop real world application feel free to contact me you can reach out to me by email linkedin or twitter all of the links are going to be in the description just for you alright enough of my introduction let's get straight into the tutorial alright guys so first of all we need to create a nexus app you can create this with these commands so i'm gonna grab this command from here and i'll paste it and i want to use npm instead of yarn so i'm gonna use a flag called dash dash use dash npm that will use npm instead of yarn and my app name will be next dash auth dash yt so now let's create the app and our nexus app is created so let's cd into the folder and before i install any kind of packages i want to do some cleanup on the app i don't want the status directory so i'm gonna remove that now git because it is a git repository and i like to create a source directory where i put all of my source code i would like to move the pages directory inside the source directory and now the pages directory is inside the source directory now we can install our necessary packages so i'm just gonna grab the command from my blog and i will paste it here so let's install them all right so the packages are now installed so i will open up the app on my editor so let's first go to the source directory then pages and open up the underscoreapp.js file i don't need this import and i need to destructure the page props i want the session and i want the rest of the page props and i need to import some component from next dot and chakra ui i need to import the session provider from next.react it will be a named import session provider from [Music] next dot slash react and i want the chakra provider from at chakra ui react and now i need to wrap this component with these providers so i'm gonna add the session provider first and inside the session provider we will add chakra provider and i will add the component in the middle the session provider will take a prop session and it will be the session from the props i guess that's it for this file let's open up the index.js file and i will remove all of this code let's create a new component i will call it home let's see if chakra ui works or not i will import a heading component from chakra ui react and i will add a heading here text will be subscribed to kills coding so let's see if it works or not so on another terminal i'm gonna run the server with npm run dev and let's go to localhost 3000 and you can see we have a heading text subscribe to kills coding and it is also styled so chakra ui is working and i'm just going to move this tab on my editor workspace and now it is looking good so now let's set up next stop to set up next dot we need to use the api directory in the pages directory so inside the api directory we need to create another track trick called auth and inside the auth we need to create a file and the file name has to be wrapped by the square brackets and the name is three dots then next auth then dot yes the file name has to be same so let's open it up so first of all let's import next up from next up this next stock is a constructor so so we need to export an instance of this so export default and let's call the next stock and it will take a parameter which will be an object inside the object we will have a provider's property which will be an array and inside the array you can pass all of your providers like github provider google provider and so on now before we set up any kind of provider let's learn how to check if our session already exist or not so let's go to index.js here we need to import a hook which is used session so import it will be named import use session from next.react and let's call the use session hook and this will return you an object so i'm gonna destructure it it will have a data property which will be the session actually but i'm gonna rename it to session so if the session exists we're gonna render some text else we're gonna render a different text so if session exist we're gonna render a heading text and the text will be [Music] you are signed in else we're gonna render a different text i'll copy this line and it will be you are not signed in i will delete this one and you can see it's telling me that you are not signed in because the session is null so let's add a button here to sign in so button from chakra ui and we need a function called sign in it will form next react so let's add the button and the text will be sign in and let's add a on click handler oops this has to be inside a fragment and we need to add a on click handler and we're just gonna pass the sign in and let's click on sign in and you can see it is telling me error because we haven't set up any kind of provider so now let's do that so now let's set up our provider we're gonna set up the github provider at first then we're gonna customize our ui a little bit then we're gonna set up other providers like twitter google then email and also we're going to add a database so let's set up the github provider first of all you just have to go to this url github.com settings slash applications slash new and here you need to create a new oauth application just give your application name i will call it next stop yt and give your homepage url i will give my website and then give your authorization callback url and this callback url will be same for all the providers which is http depending on the environment if you are on production then it might be https but on development http localhost 3000 slash api github the last part is the provider name if you are using twitter then it will be slash call backslash tutor and now register application and it will give you a client id and a client secrets and we need to store them in an environment variable so generate a new client secret so this is our client id and this is our client secret id and don't worry i will remove the app after recording this video we need to store these ids in environment variables which is pretty easy to do in next year's just create a new file on the root of your project and the file name is dot enb dot local it will be a dot file so that's why it will be hidden so let's create a variable github id and github secret so i'm just gonna copy this id also the secret one now the common convention for environment variables is to use capital letters and instead of space use the underscores that's it for the github environment variables let's go to the next stop file and let's import the github provider from next dot slash slash github and let's add the github provider inside the array so github provider and we need to pass an object we need to pass the client id and the id will come from the environment variable so process dot env dot i'll just copy the variable name and also client secret i'll copy this and the variable name will be github secret okay so that's it for the github provider let's go to our app and go to the home page and now let's click sign in and you can see it has taken us to another route localhost slash api sign in and we haven't created this page this page was created by the nextup so let's click on sign in with github um try signing in with a github account and we have an error client id is required um we have provided the client id of i guess i have to restart the server sorry for that so again npm run dev and now it should work fine so we just need to refresh this page so now let's click on sign in with github we should not have any error and it has taken us to this page so let's click on the authorize button and you are being redirected to the authorized application and you can see we are on the home page but this time it is saying you are signed in because this time the session is available that's why it is saying you are signed in so let's see what is inside the session so i'm going to console log it and let's open up the dev tool and ignore this morning we have an object printed out and inside the object we have an expires property which is a date and we have a user object which is containing all of the user so we can display them and instead of just this text you are signed in we will just use signed in as the we will print out the user email so session dot user dot email and you can see it is telling us signed in as deadonjohn there gmail.com okay so now that we have the functionality of sign in with github now let's see how we can sign out it is pretty easy to do i'll just copy this button and i'll paste it here instead of sign in it will be sign out and again i need a wrapper so i will use fragment and we need to import the sign out function from next up and we need to trigger the sign out function on click so now let's click on this button and you can see we are no longer signed in we have a sign in button so we have successfully signed out from our github account and you might have noticed that there was a page refresh and that's not a good user experience but we can prevent that and that is pretty easy to do so i'm gonna create a function const handle sign out and we're gonna call the sign out function now when calling the sign out function we can pass an options object and inside the options object you have to pass redirect property which will take a boolean value we're gonna pass false by default it is true that's why we have the page refresh and instead of sign out we're gonna pass handle sign out so let's see so i'm gonna sign in again sign in with github and you can see we are now signed in now if i click on sign out we shouldn't have page refresh and you can see we didn't had page refresh and you can see that even after page refresh we are still on the previous page but if you want to redirect the user to a different page while signing out you can pass another options call callback url so i'm gonna pass that i'm gonna pass up url slash sum which doesn't exist so let's sign in again sign in with github and now let's click sign out you can see that we are no longer signed in but it didn't take me to this route the reason is redirect false so if you want to redirect your user to another route you need to have page refresh but we can prevent that still so let's see we're gonna make this function async and i'm gonna import the use router hook from next router and let's add curly braces now this signup function is an async function so we need to avoid this so await and it will return you and data object so const data and this data has a url property which will be equals to this callback url so after sign up we can redirect the user to this url using the use router's push method so let's get the push method const push and it's from use router and let's push the user to data.url so i'm going to create another file in the pagestrick tree i will call it sum.js and let's just create a component so now let's sign in again let's sign in with github and now let's click sign out and you can see we are redirected directly to the slash sum route so that's how you handle sign out functionality and before i implement other providers like google twitter and email i want to style these pages a bit and also i want to create a custom sign-in page so let's go to underscoreapp.js file i'm going to import the grid component from chakra ui and i'll wrap the component component by the grid component and i will add some style with sx prop i want the height to be 100 view height and place items to center and padding on the horizontal side will be fibre oops it will be a string then text align will be center i guess that's it now let's go to the index.js file and again i will import the grid component and i will replace these tips with grid i will make place items to center crit row gap it will be one ram obsession b comma all right so our page is looking pretty good now let's create the sign-in page so the custom sign-in page for out will be slash auth slash sign-in so i need to create another directory in the pages directory it will be auth and i'll create a file sign in dot jsx so let's create a component and you can tell next stock to redirect the user to slash slash sign-in page when the sign-in function will be called so just go to the next stop file and inside the next dot pass a property called pages which is an object and here you can specify all of your custom pages so for sign in it will be slash out slash sign in so let's see if it works or not now i will click on sign in um 404 page could not be found upstairs should not be capital letter it should be lowercase i so let's go to the homepage again so let's click on sign in and now we are on slasher sign-in route another thing that you might have noticed that we have a callback url query parameter which is referring to the home route because we are on the home route before we entered the sign-in page it will be used to redirect the user to the previous visited page after the user is signed in but there is a problem with just calling the sign in method you might have noticed that the page was refreshed but we don't want any page refresh let's just go to the index.js file instead of calling the sign in method i'm gonna create another function const handle sign in instead of calling the sign-in method i'm gonna use the push method to redirect the user to the sign in page so i'm going to call the push method and the route will be slash out oops slash auth slash sign in now sing in sign in and i'm gonna pass the handle sign in method so let's go to the home page again and let's click on sign in and you can see we are now at the sign in page without any page refresh but we don't have the callback url as query parameter so we need to manually pass a callback url the use router hook has a property called as path the as path is just the current route for example if you are on home page it will be just slash if you are on sign in page it will be just slash out sign in so we can pass this as spot as a callback url in the query parameter so i'm going to use template string and let's pass a callback url and it will be the spot and now let's click sign in and we have a callback url as parameter which is equals to slash that means previously it was the home page that we have visited so let's go to the sign in file now to style the page we need to import a lot of component so i'm gonna paste the code all right so we need these components so we have imported the usted hook use router hook again and we have imported some chakra ui components box just a container then button component grid component then a heading component a vertical stack component for stacking components on top of another then we have some form components and an input component and a chakra factory function then we have imported the session hook then the sign in sign out function and then some icon from react icons okay so first of all we want to prevent the sign-in user to visit this page so we need to use the use session hook so use session and let's get the session it also gives us a status property um we have an error it's a react hook error okay so the sign in function name has to be uppercase s also here so if the status is loading we want to display a message so if status is equals equals to loading we're gonna return heading and the text will be checking authentication but if the session is present we're gonna redirect the user to the home page so if session is present then we're gonna return a component the message will be you are already signed in after five seconds we're gonna redirect the user to the home page so timeout will be 5000 and we're gonna run the push method and the url will be slash so let's get the push method so const push from use router so now let's add a box component instead of this dip [Music] so box and i'm going to add a v-stack component vertical stack vertical stack is just a flex container and here i'm gonna loop over an array of objects so and now i'm gonna create a provider's array actually it will be an array of object which will contain some information about the provider so const providers it will be an array of objects i'm gonna paste them here so these are the array of objects it has a name property which will be the provider name and icon property which will be the icon that we have imported so let's loop over the providers array providers dot map the first item will be the provider which will be an object i'm gonna destructure it so it will have a name and icon so let's return a component i'm gonna return the button component and it will have a text sign in with the provider name let's pass some props first we need to pass the key it will be just the name then i want a left icon in the button so left icon will be the current icon and you can see we have three beautiful buttons so let's add the on click handler and i will pass a function called handle or sign in and i'm gonna call it here and pass the provider name and before i implement the handle or sign in function let's add some property so text transform will be uppercase and width will be hundred percent so let's implement that handle or sign in function so const or sign in it will be a function which will return another function the first function will take a parameter which is the provider name and the outer function we'll just call the sign in method now by default the sign-in function will redirect you to the sign-in page but you can pass the provider name directly inside the sign in function call if you do that you will not be redirected to any other route you will be directly login with that provider for example if you just pass github then you will be signing with github you will not be redirected to any other page so here in this case we will just the provider so let's see if it works or not so now if i click on this button we will be signed in with our github account so let's click it so authorize that on june and it says checking authentication you are already signed in and we should be redirected to the home page okay so we are now at the homepage signed in as that on join there gmail.com so our buttons are really working if i try to visit the slash auth sign-in page we should not have access to the buttons okay so you are already signed in we don't have access to the sign in buttons so our sign in page is almost ready now let's add the input form for email so outside the vstack component i'm going to create a form element now we have imported a function called chakra it is a factory function basically with this you can create any html element a chakra ui component here we want to make a html form element to our chakra ui form component so it is pretty simple just use the form i don't need action but instead of just form we're gonna use chakra dot form and now it is a chakra ui component and inside this form component we're gonna add a form label and the label will be email address and i'm gonna add an input type will be email and to store the email value we need a state so let's create a state use date state name will be email and the value will be empty string so on change we're gonna set the email state so e and set email it will be e dot target dot value then we need a button component and the button text will be login type will be submit which will be 100 and margin on top and bottom will be five now let's create a handle submit function so const handle submit and let's get the event and we want to prevent the page refresh so prevent default and if email is just an empty string we're gonna return false and let's call the sign in method and we need to pass the provider name which is email and we need to pass an object and we need to pass the email value so just pass email now for email login you can prevent the page refresh but for other providers you cannot so i'm gonna pass another property which is again redirect which will be false and on the form let's add the onsubmit prop and it will be handle submit okay so that's it for our sign in page now let's handle the twitter and google login functionality then we will learn how to set up the email login functionality so first of all just go to developer.twitter.com then you need to request a developer account if you are approved then just go to the dashboard create our new project then just go to the project and on the bottom here is an option add app and make sure it is development and then go to next and give your app name i will call it next authy then next and here it will give you this api key an api secret key we need to store them but before that we need to go to this link enable third party authentication and let's go to the bottom it says authentication not set up so let's click on setup so click on oauth one and make sure you have checked this request email from users and add permission to read and give the callback url which will be same localhost 3000 slash api slashout slash callback then the provider name which is twitter and give your website url i'm gonna give mine then a terms of service url i'm just gonna paste a dummy url and let's click on save and now we need to store these api keys in our environment variables so let's open up the dot env file and i need to create two more variables i'm just gonna paste the variable names so i will copy this api key and i'll paste it here and now the api secret key now let's open up the next file and let's import the twitter provider and let's add the provider twitter provider and i'll just copy paste the property and values from here we have used the same environment variables so now let's see if it works or not let's click on sign in and before i click on the button i have forgot to restart my dev server so i'll kill the server and npm run dev and now let's refresh the page and now let's click on sign in with twitter okay so it has redirected us to this page now let's click on authorize app reacting you back to application and you can see we are now signed in and we have been redirected to the home page so our twitter sign-in functionality is working so now let's set up google provider so just go to next.js.org provider slash google you will see this page and you will have this you will have these two links so just click on this one the configuration link i will open this up on new tab and you'll see this page you might need to create a new project if you don't have any i already have one project after creating the project click on this create credentials and click on oauth client id and our application type will be web application and give your app a name i'm gonna call it next auth yt and then add a uri for authorized redirect urls and again the callback url will be http slash localhost 3000 slash api slash auth slash callback then the provider name which is google and now let's create ops not 300 3000 now let's create and we have this client id and client secret so we need to store them i will just copy this environment variable names and let's go to enb dot local and i'll paste it here i only need the environment variable names so the client id is this one and [Music] client secret is this and now let's go to next stop again i will copy this import statement and i'll paste it here and also this one all right so our provider is set up now let's restart the server so now let's click on sign in and let's click on sign in with google and choose your google account i'm gonna choose this one and again you are already signed in and we have been redirected to the home page signed in as that engine at their gmail.com so we have successfully set up the google authentication now every time you sign in with the provider all of the session data is stored inside your browser so that's not really that useful you need to store your user data in some kind of database so now let's set up a database where we will store all of our user data i'm going to use mongodb which is a nosql database you can use whatever you want let's go to the next stop and if you go to the bottom you will find the section adapters and here you will see all of the database that next door supports by default we have dynamodb firebase mongodb so we're going to use mongodb we're going to use mongodb atlas as our host so let's setup mongodb atlas so just go to cloud.mongodb.com then you will be redirected to this page where you need to log in with your account create an account if you don't have any but i'm going to use google to log in so after you have logged in with your account you might need to create a new organization if you don't have any i already have one i'm going to choose this one let's create a new project i will call it next dot yt and i don't need any other members so let's create project so build a database i will go for free let's create choose your cloud provider and the region i'm going to choose the default one and if you want to change the cluster name you can do that i'm not gonna bother about it so let's create cluster and we need to create a database user so i'm gonna give my name and also a super secure password let's create user and on the bottom you will you have to add an ip address i'm gonna add my current ib address and let's finish and close and let's go to database mongodb is creating our cluster but let's go to the network access and click on edit now my current ib address doesn't work so i need to use allow access from anywhere so let's click confirm and again let's go to database and it will takes a minute i will be right back when it is done alright so our database is now ready let's click on this connect button and choose the method we need to choose the second one and make sure the driver is nodejs and the version is the latest one and this is our connection string and let's go to the mongodb provided talk we need to install these packages so i'm gonna copy the command and i will kill the server so let's install the packages all right so our packages are now installed let's go to the dot env file and we need another environment variable i'm gonna copy the variable name which is mongodb uri and the value will be the connection string i'll copy this now instead of this password we need to give the database password not your mongodb account password your database password and we need to give a database name so let's create a database i will close this model let's go to browse collections and click add my own data and let's create a database i'll call it auth and the collection name test doesn't matter here so let's create so we have our database and i will remove this placeholder and database name will be up and now we need to create some files i'll create a directory inside the source directory i will call it database and i'll create a file i will call it connect db dot yes and i'll copy the whole code from here and i'll paste it here basically it is just getting the environment variable if the environment variable doesn't exist we are throwing an error and then we are just returning a client promise you don't have to bother about them they are already configured and now let's go to next stop and we need to import that so import client promise from dot dot slash starter slash we have to go one step back again then database then connect tv and we need to import the mongodb adapter i will just copy this thing now paste it here then we need to add another property which is adapter and adapter will be mongodb adapter and just pass the client promise and now let's just restart the server with npm run dev and let's just refresh the page and now let's click on sign in again and sign in with google i will choose this one again we are signed in but now let's go to the database and let's just refresh and you can see we have bunch of collection we have a accounts collection we have all of the information the id token user id then expire set then sessions then the users we have the name email then the image okay so now let's sign out and in the database let's just refresh and let's go to sessions you can see we don't have any session because we have logged out so our mongodb adapter is working fine and it has redirected us to the sum route so finally now let's implement the email authentication system so let me show you the documentation about email provider now when you submit a email address on the client side next stock will send an email to that email address that email will actually contain a magic link and you can sign in with that magic link no password is involved here so to send an email first of all we need to install a package called nodemailer i will kill the server here so let's install the package npm i node mailer so let's install it alright so node mailer is now installed now to send an email we need to use an email service i'm going to use send grid so if you want to follow along with me just go to sendgrid.com and then create a new account if you don't have any and then just sign in with your account now after you have logged in with your account you might need to create a sender account if you don't have any so just create a sender account with the necessary information after that just go to email api then go to integration guide now choose smtp relay now it will ask you to give an api key name so i'm just gonna give test so let's create key and send grid has given us this api key and we need to store this information in our environment variable so click on i have updated my settings and let's store them in our environment variables so in the documentation uh where is that here so we need all of these environment variables so i'll copy them and i'll paste them in env file i will remove this values email server user will be the username which is api key then the email server password which is this key the email server host will be this smtp.sengrid.net and then email server port will be 587 because we are on development then email from will be the sender account in my case it will be that on john at the rate gmail.com all right so let's go to next.js and let's import the email provider actually i will copy code from here and let's add the email provider so i will copy all of this code from here and we don't need to change the environment variables because we have used the same environment variables from here so after the google provider i will paste the code all right so we are all set now let's run the server npm run dev so let's refresh the page all right so now let's click on sign in i'll put my email address and let's click on login and on the console we don't have any error so now let's go to gmail and most probably your email will go on spam so go to spam and you can see we have an email from localhost 3000 and here we have this magic link so let's click on it and it has opened up a new tab and you can see checking authentication you are already signed in and you can see signed in as that on june gmail.com so the email authentication is working fine so we have successfully implemented the authentication system with github twitter google and email so finally now let's see how we can protect our next year's api route and a page so first we are going to create a protected route so inside the api directory i will create a file called protected.js and i'll close these files for now so first we need to import a function called getsession from next.react from next dot slash react and now let's create a handler function and let's export that so the handler function takes two parameter one is request another one is response so we need to get the session using the get session method so const session it will be asynchronous so i'm going to make it async and let's avoid the process and let's call the get session and we need to pass an object and inside the object we need to pass the request if the session exists we're gonna return our response so if session exist we're gonna return oops return rest.send we're gonna just send that session else we're gonna send a response so return rest start send not authenticated you can see that i am currently authenticated with this email and if i just go to localhost 3000 api slash protected i should get the session all right so we have this object session username on john then email that on jonathanwhichgmail.com and now let's sign out and here let's refresh the page and you can see not authenticated so now our api is protected and that's how you can protect an api using the get session method so now let's see how we can protect the page so i'm gonna close this file i'm gonna create a new file inside the pages directory i will call it protected dot js and here let's create a component now there are two ways you can protect a page you can protect the page using server-side rendering or client-side rendering so we're gonna see both so first let's see how we can protect a page using server-side rendering again we have to import the get session function so import not import import get session and we will also need the use session function from next dot react so now let's export a function called get server side props now this function takes a parameter called context i will call it ctx and obviously it will be an asynchronous function now we need to call the git session function and just pass the context object and it will return us the session object so const session await and now we just need to return the session as a prop so this will get the session and pass it as a props and now we need to call the use session hook now when we first use the use session hook it sends a request on the client side it will not call any api request because the session already exists in our component so let's get the session and it will also give us the status so this will contain the session and status can be either loading authenticated or unauthenticated and just because we already have the session that's why status will never be loading it will be either authenticated or unauthenticated if the status is unauthenticated we want to display a message that this is a protected page you are unauthenticated so if status is equals equals unauthenticated we're going to return a heading component so i will import that oops it will be named import from chakra ui react and i will return a heading component and the text will be you are unauthenticated this is a protected page else we want to render the user email so again heading and it will be session dot user dot email so let's see if it works or not so let's go to localhost 3000 slash protected and you can see you are unauthenticated this is a protected page so let's go to the login page so it will be slash auth slash sign in [Music] so let's just log in with google i will choose this email and you can say you are already signed in and if i go to the protected page you can see it has printed out the email and if i refresh the page is still showing me the user email so our page is now protected but you might want to redirect your user to the sign in page from the server side you don't even want to show them the protected page so let's see how we can do that so we just need to check if session exist or not if session doesn't exist we want to return an object and that object will have a redirect property it will be an object too we just need to pass destination and destination will be a route where you want your user to redirect so it will be slash auth slash sign in so let's see if it works or not so let's go to the home page and i will sign out all right so i'm not signed in and you can see you are unauthenticated this is a protected page so i will refresh the page i should not see the protected page i should be redirected to the sign in page and you can see i am now at the sign in page so that is totally optional that's up to you but i just wanted to let you know that you can do this so this is how you can protect a page from server side now let's see how we can do that on client side actually we have seen how to do that on client side if you don't pass the get server side props it will work on client side so i will just comment the get server side props function and let's go to the protected page it should give me an error because we are not handling the status of loading all right so you can see we have an error because we are not handling the loading status so we can handle the status of loading so i'll just copy this code and instead of p i will use heading and if i refresh the page you can see that it's loading and now you are unauthenticated this is a predicted page so this is how you really protect a page from client side using the use session hook but you can do more than this using the use session hook you might tell the use session hook that this is a protected page on the hook call by passing an object and you can pass a property called required to true if you pass required to true that means that this is a protected page authentication is needed if the user is not authenticated then the use session hook will redirect you to the sign in page so let's see if it works or not and you can see that it is redirecting me to the sign in page all right so now i'm in the sign in page but you might not want your user to redirect to the sign in page you want to do something else and also you might have noticed that it had a page refresh so you might also want to prevent that to stop the default behavior you can pass a function called on unauthenticated this will be a function if you pass the unauthenticated function then the default behavior will be stopped and i will go to the protected page and you can see it is showing me loading it will not show anything because status will be always loading so in on authenticated function you can do whatever you want you might want to redirect your user to any other page or anything so i'm gonna redirect my user to the sign in page using the use router's push method so that it will not have any kind of page refresh so i'm gonna import that oops so let's get the push method and let's call the push method and i'm just gonna copy the url so i will refresh this page and you can see it is saying loading and now it has redirected me to the sign-in page without any page refresh so this is how you can protect a page using the use session hook from client side so that's it that's all there is that i wanted to show you in this video you can see that authentication with next stop is super super simple we have write tiny amount of code for authentication logic if you want to do that from scratch you have to write tons of tons of code if you don't believe me you can try it if you want so that's it if the video has been helpful for you don't forget to like share and subscribe to my channel if you have any question please comment down below if you want to suggest me any kind of topic please do let me know in the comment section if you want to get daily tips and tricks you can follow me on linkedin twitter or instagram as that anjon and i'll see you in the next video goodbye [Music]
Info
Channel: Cules Coding
Views: 24,423
Rating: undefined out of 5
Keywords: coding, programming, trailer, webdevelopment, developer, material-ui, programmer, nextjs, reactjs, javscript, html, css, framework, web, jamstack, static site generation, server side rendering, client side rendering, ssg, ssr, csr, mongodb, dynamic routing, api routes
Id: tgrvKGPmI04
Channel Id: undefined
Length: 71min 7sec (4267 seconds)
Published: Wed May 11 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.