Next.js Auth | This is the Easiest Way To Build Auth with Cookie Sessions

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
Hello friends today you are going to learn cookie based nextjs authentication without using any free or paid off libraries in the example we have four pages the homepage is visible to everyone the profile page is visible to logged in users the premium page is visible to Pro members and since I'm logged in I cannot see the login page if you check the cookies you are going to see here the encrypted session when I log out it's going to remove this cookie let's log in again on the profile page we get all this information from the session and I can cancel my premium membership as you can see it updates the session and if I try to reach the premium page I cannot see the content anymore I can also change the username in a similar way if I refresh the page my session remains the same and let's say I'm a premium member and I didn't cancel the membership but maybe the admin cancelled or I didn't pay the bill or maybe they blocked me in this case again my session will be updated in the subsequent request because each time we will search for the user in the database and make sure that they are not blocked or the subscription is not cancelled and all this encryption and decryption will be on on the server site with next J server actions and we will be using a secret key HTTP only and secure options to ensure the security of our cookie storage so let's see how to implement all these functionalities if you want to see more tutorials like this please like the video and let me know in the comments what you want to see in the next tutorials so if you are ready let's get started okay hey I created a new nextjs application and in this app as you can see we have the homepage and it says this page is visible to everyone I'm going to create my other Pages the first one will be profile page I'm going to paste my page here let's say profile page I'm going to remove that second one will be premium page page again I will paste my page and change the component name and finally the login page login page okay so let's show our links on the Nar to do that we are going to need a new component inside source folder I will say components and the first component will be nowar by the way if you don't know typescript don't worry there is nothing complex you are going to understand everything I will create my component let's say nowb bar and inside I'm going to create my links we are going to be using next xjs link let's say homepage three more and premium profile page and the login page let's use it in our layout so we can see our nebar on eror page so let's cut this children for now and firstly I'm going to create a container and inside I'm going to call my now bar and the content will be the children homepage profile premium or login page okay they are here right now I'm going to give some style so we can see better of course styling is not our concern for this video I'm just going to copy and paste but you can find the style in the GitHub repos hisory I'm going to open up my Global CSS and paste my style here okay it's much better right now homepage premium profile page and login now we are ready to take care of authentication I'm going to open up my terminal let's create and I will say mpm install iron session so what what this Library does is it basically takes the user information user ID username or whatever and it encrypts that data creates a session and sends it to the user cookie and after when user makes any request we can take that cookie we can decrypt on the server site and reach the user information when we start you are going to understand better by the way we are going to need here one more component and it's going to be the log out button let's open up our menu and inside components I will say logout form let's create quickly it's going to be a form and inside let's say a button that says log out let's use it in our NB bar like that okay so what we are going to do firstly inside login page we are going to have a form here the username and the password using credentials we are going to search for the user in the database if the credentials are correct we are going to create a new session using our library and when we click on this button we are going to remove our session and we are going to need one more function and this going to check the user session for example in the premium page we are going to check the user and if the user is a premium member they will be able to see the content here so again we are going to have three actions login log out and get session so let's come here in the source folder and create actions the first one will be export const get session is going to be an async function and two more this is going to be login action and log out before creating them we are going to need some configurations to do that again inside source folder I'm going to create a new file and it's going to be let's say library and here we are going to decide which user information that we want to store let's create an interface export interface or type whatever you want session data we can store user ID it's going to be a string or number depending on your database we can store username again string what else it can be it can be user image by the way it's not a type we should use semicolon and we can store is pro it's going to be true or false so I will say bullion and you can add any additional information but for now it's enough so let's create our session options export const session options and its type will be session options that comes from Iron session here firstly we are going to need a secret key and this secret key should be this password should be at least 32 characters to generate this password you can use your terminal and say open SSL random base 64 and 32 characters okay we can use it but remember it's a secret key so you should store this in anv file file I'm going to come here this is the root folder and I'll say em and let's say secret key and I'm going to paste it here of course if you are using EMV file make sure that it's in the git ignore file I will say process. em and secret key and after that we are going to need the cookie name you can give here any name you want I will say llama session basically when we create our session we are going to see it in our browser storage inside cookies as you can see it's empty for now but when we create we are going to see this Lama session here and finally I'm going to add here the cookie options the first one will be HD TP only in this case it prevents the client side JavaScript from accessing our cookie we are going to use it only our server site and I will say secure if you say true your connection should be https but we are using Local Host so it's going to be false for now but if we are in the production mode it should be true so I'm going to come here and say not EMV it's going to be development or production in our case it's going to be development and I can write here a condition if process EMV do not EMV equals production it's going to be true otherwise it's going to be false and what else you can add here you can add the maximum age you can give any time period but for now that's enough let's get our session using this option I'm going to copy this and I'm going to open up my actions let's close this menu and here and I will say import session options and session data from our library oops what was that of course cap put a letter and let's try to patch our session I will say const session await get iron session and we are going to pass here our session data so we can use only those items nothing else and inside as you can see we should pass the user cookies and our options to take the user cookies we are going to be using cookies function as you can see it comes from next headers if you remember this cookie includes our encrypted session to decrypt it we are going to need our session options basically we are going to be using this secret key and we are going to decrypt our session in this case we will be able to see our user ID user name or whatever let's return this return session and let's see these on our nowb bar I'm going to close them and open up nowb bar and let's say const session get session function if you remember it's a promise because it's an action by the way for Server actions you have to use use server directive so everything inside this function will run only on the server site and if you are using all your actions in one file you don't have to write them one by one just copy this and use it on the top of the file just like that right now we don't need them okay let let's come back and it's going to be async and we are going to await our function let's see what's inside I'm going to open up my terminal and as you can see there's an empty object here that means we don't have any session right now so using this session object we can hide or show our log out form we can say if it's empty don't show the log out form because we are not logged in yet but instead of writing this condition like that there's a better solution I'm going to open up my library and create here a default session export const default session its type will be session data again and I'll say is loged in and by default it's going to be false right now we have to use it here and its typee will be bullan I'm not putting here question mark because in any case even if we don't have any session is logged in will be false so let's come back and here I will say if session dot is logged in is not true we are going to update our session and is logged in properly will be the default value which is false so I will say session dot is logged in it's going to be default session dot is logged in again at the beginning our session is an m to object in this case here is going to be false and we are going to pass the default value here so when we return our session we are going to see that is logged in is false right now so let's use this value here I will say if session is logged in show this log out form as you can see right now it's hidden when we log in we are going to see that button here so you can do the same thing for the login page and profile page you can say if it's not logged in don't show the profile page or if it's logged in don't show the login page but I'm not going to do that because it will be easier to understand the prot Ted routes we can directly click on them instead of using this URL so it can stay like that right now you know how to use sessions let's remove this I'm going to close everything and open up my login page and inside this page we are going to need a form to do that I can create a new component login form and it's going to be a form and inside we are going to have two inputs the first one will be username let's say required and the placeholder will be again username so I can do the same thing for password just like that and after I'm going to create a button that says login let's use it on our login page I will call my login form perfect so when I enter a username and password and click on this button we are going to dispatch our login action let me close here and inside this form I will say action and we are going to call the login function so how we are going to reach those values it's really easy because we are using name here username and password so using those names we can reach our data let's open up actions again and inside login firstly I'm going to call my session await get session we can directly call this function here and it's going to return as our user information and again we are going to update our session but firstly we should check the username and password I'll say form username to reach this data we are going to be using form data and its type will be form data and we are going to get the username and I will say as string and one more is going to be password and using this username and passwords we can search for our user I'll say check user in the database of course for this tutorial I'm not going to create any database it depends on your project basically we are going to search for user let's say await DB and get user and we are going to pass here to username and password and we are going to check the user if it exists it means our credentials are correct so we can update our session but for this tutorial let's create here a dmy data I will just say username let's say John let's say is pro it's going to be true basically I will say if the form username equals John the credentials will be correct so we can return this username and is pro and update our session using those information so I will say if form username doesn't equal the username in the database we are going to return an error let's say error wrong credentials and and if everything is okay we are going to update our session so its username will be let's give any user ID again it's going to be the ID from the database let's say username it's going to be form username and session dot is pro will be is pro again it comes from the database and after that we are going to save our session do save and after saving the session we can redirect our user to the homepage so I'm going to be using redirect function it comes from next navigation and we are going to pass the URL which is the homepage let's give here any username the wrong one I will login as you can see nothing happens because it's the wrong credential but if I say John and login as you can see we are on the homepage we cannot see our log out button because I forgot writing here is logged in true it's still false but if you open up your console and inside cookies as you can see the cookie name is Lama session and it includes this encrypted value so if the user makes any request our get session function is going to get this cookie this encrypted cookie it's going to decrypt and reach the user information let's come here by the way and say is logged in SC be true let's remove this and try again as you can see it's here and our cookie is here let's close this and let's see how to log out it's really easy I will just get my session again const session get session of course await don't forget and we are just going to destroy this session using destroy function and that's all again we can redirect our user let's use this action on our component log out form I will say action and log out let's import and let's see I will click but before I'm going to open up my console our cookie is here if I log out as you can see it's gone it's that easy guys before going further I want to show you one more thing here if you remember when we write in a wrong credential here it doesn't show our error message to handle this we can use use form State hook let me show you how to do that I will say const State form action use form State hook and we are going to pass here our action which is login and the initial state will be let's say undefined so at the beginning we don't have any error message but if there's an error in the login function we are going to update our state in this case we are going to need one more parameter here and it's going to be the previous state or whatever you say and I'm going to write here its type it's going to be error and it will be undefined or a string oops single pipe and here we have the form State and the form data so let's say any and form data as you can see there is an error here because we are using a react hook and if you are using a hook your component should be a client side component so I'm going to come here and say use client by the way I'm going to pass here this form action right now basically when we click on this login button it's going to fire this form action and this action has a state and its value is is undefined at the beginning and it's going to pass this value to the login action it's going to take that value and the form data if there is an error it's going to update our state here right now we can show our state under this button let's say if state has an error show here a tag and state. error let's try I'll say Jane any password Here login and wrong credentials this is what we exactly want and if it's correct we are going to be redirected to the homepage okay awesome what about this profile page again we can call our session and right here do username let's close everything here and open up profile page and I will say a p tag welcome let's make the name bolt and I will pass here session. username of course we don't have our session let's call I will say async con session get session function by the way it's going to be of course a wait as you can see welome John but there's a problem here if we log out we can still see the profile page and it says welcome and we don't have any username so what we can do here we can write a condition and after checking the session if the user is not logged in we can redirect the user to the homepage I will say if session dot is logged in redirect user to the homepage again don't forget it should be next navigation and as you can see we are on the homepage right now if I click it doesn't let me to see the profile page okay and let's create here one more element and it's going to be a Spen and let's say you are a premium or free user so again we are going to need a condition here if session is pro we are going to write here premium if it's not it's going to be free let's log in again don't add a password here and and you are a premium let's say user okay and after that I will create here a form that the user can cancel the premium membership or if it's the free they can buy a premium membership so I will say a form you can create a new component but I'm just going to write it here you know how to do that a button and I will check again if session is pro right here cancel if not byy as you can see we are already premium so we can cancel so let's create our fourth action I'm going to open up actions and let's say export const switch or let's say change premium it's easier to understand I will say async function and again let's call our session get session function you should update the user in the database but we don't have a data base so I will just update this is pro variable if it's true it's going to be false and vice versa I will say is pro equals session do is pro here is not important as I said it should be your database connection and finally after updating the user in the database you can update the session is pro it's going to be is Pro from the database let's save our session so it's going to update and after we are not going to redirect our user to anywhere instead we are going to refresh the data inside this page so when we cancel the premium we can see the result here immediately to do that we can use revalidate path function it comes from next cache and we are going to revalidate the data in the profile page so let's use it here I'm going to import and let's see I'm going to click as you can see our session has changed if I refresh the page it's here and again if I click this time the premium m user so I can do the same thing to change my username I'll say form insight and input name will be username again required and the placeholder will be our previous username which is session. username and after a button and I'll say update let's create another action actually I can copy and paste and let's say change username again we are going to need a form data and as we did for the login page you can use use form State hook and if there is any error on the database you can show it here but anyway you already know how to do that I'm not going to waste your time I will just take this new username it's going to be from data doget username and again as string and I will update my username it was John but this time it's going to be this new username and I'm going to update my session and after we are going to update the data on this page I'm going to save let's say mic didn't change because we didn't call our action change username let's try again chain and perfect okay awesome I can cancel premium by premium change the name and right now let's protect our premium page I'm going to close here and open up the premium page and again we are going to need our session get session don't forget a wait here and again I will write exactly the same condition here if we are not logged in we shouldn't see this premium page so I will say if session is not logged in redirect user to the homepage and we are going to need another condition if session is not pro it's not a pro member we are going to return let's create a do not premium and inside I will create a title only premium users can see the content and we can add here a link that user can go to the profile page so I will say go to the profile page to upgrade to premium and I'm going to add here my URL which is profile page as you can see there is no problem because we are a premium user but if I cancel my premium account as you can see only premium users can see the content so we can visit our profile and buy a premium after coming back we can see the content let's write any bummy content here it's a really great premium content but anyway buying premium is free everything is perfect but there is a small problem here of course we can buy or cancel the premium but what if the admin of the application just cancelled are premium or the admin of the app decided to ban or block this user in this case we cannot update the user session or destroy this session as an admin because it has to be the user we are using the user cookie so we can not reach this data as an admin so in such situations we have to validate the user in the database whenever we make a get session request so instead of directly returning to s s each time we are going to search for the user in the database and we are going to check if the user is blocked or banned or is not pro anymore and after we are going to return to validated session again check the user in the database and update your session so I will say is blocked for example and it's going to be the value in our database and again I can create here a dum data is blocked is blocked and of course we should update our type is blocked and also I'm going to check the is Pro value because admins can cancel that and you can validate here whatever you want but these two are really important we have to check them for each request for small applications if you don't have the admin functionalities or any payment functionalities you don't have to do that but in this case it's better to use it like this and right now you can check is blog property on your homepage and you can show a different component here you know how to do that it's exactly the same you will just check your session and redirect user to the homepage or show another component just like this and if you check the official documentation you can see here some examples I'm going to zoom in as you can see nextjs Pages nextjs app rouder examples and inside you can see how to use it on the server components with actions client components and API routes there are tons of examples here and in this tutorial we have used the server actions it doesn't have is pro is blocked properties it just uses the username and as you can see each time it's searching for the user in the database so if you have any sensitive information you might want to check for each request and as I said you can come here and check the other examples if you are using API route and nextjs middleware you can find the examples here but for now the that's enough this is how you can easily manage your user session without using any third party off Library remember iron session is a session management Library it's not an off library with iron session everything is under your control so you can create any advanced method you want easily and it's much faster much easier to use and that's all if you want me to create more advanced tutori about authentication and authorization please let me know in the comments I hope you enjoyed this tutorial if you learned something new today please like the video you can support lamade by joining the channel or using the link in the description below I hope I'll see you in the next tutorial goodbye
Info
Channel: Lama Dev
Views: 20,436
Rating: undefined out of 5
Keywords: next.js, next.js auth, next-auth, next.js authentication, next.js authorization, next.js cookie, next.js session, next.js cookie session, next.js 14, next.js app router, react, react auth, react.js, iron-session, cookie based auth, authentication, authorization, next.js user roles
Id: p_FiVGxyksI
Channel Id: undefined
Length: 39min 49sec (2389 seconds)
Published: Wed Feb 21 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.