Next.js + Strapi - User Authentication

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
okay so this is probably going to be a long one so in this episode we are going to create user authentication for our application and our strappy backend of course so how is this going to work so we are going to have this paid articles page like you can see right here when you click on it because we are not logged in and we cannot see those payday articles we need to log in so you just log in you enter your password and you click login now you can see those paid articles so in this episode we are going to learn how to create that login form how to create user authentication on your strappy side and how to handle all of that in your nexjs application so let's get started so before we begin let me just show you quickly our strap is set up so i created this paid articles content type and i have two paid articles in it there it consists only of title and body next thing i did i added paid articles into our navigations so if you go to the page right now you see this paid articles link but if i click on it i of course get four or four because we still haven't created that page next thing you need to do you need to go to roles and permission actually to users first of all and i created one test user so you just do add new user what is important here is to set that user role to be authenticated of course you can create your own roles uh read this therapy documentation for that but i'm going to use this pre created role which is called authenticated next thing you need to do you need to go to roles and permissions and of course whenever you create a new content type it won't be publicly publicly available right away and we don't want that in this case so you ignore this public but you click on authenticated and for authenticated users we set count find and find one for paid articles and that's about it so you handled your strappy authentication this way by just clicking a few buttons in the stripy admin so our strap is already set up next thing i want to do i want to show you how this authentication works from a bird's point of view first of all we need to create paid articles page so we are going to create it in pages and i'm going to called call it paid articles dot js of course next thing i'm just going to bootstrap this to just be a normal page okay so this is our page as you can see it's just a normal page it's a function paid articles we are exporting it right here uh we are using get server side props which has nothing in it as of now of course we need to get public runtime config so that we can access our api and that's about it and it says paid articles right here so when i save this go to our browser now if i click on paid articles you get to this page great so first thing i want to show you how we can't at the moment access our paid articles and you of course are going to do it just like we did it a million times before in this series so we are just going to fetch paid articles api endpoint we are going to set them to be articles and then we want to pass them as props to our component so i'm just going to set this to be articles equals articles of course to access them here you just do this and let's see if we can log them out okay so save this right now go to our browser refresh it and if we take a look at our console as you can see we are getting the object but that object says error forbidden message forbidden and status code 403 this is because this is a protected route on our api so we can't access it this way so there are things that we need to do to be able to do that so first of all what we need to do we actually need to log in we are just going to hard code logging into our application uh for now and then we are going to create that login form and everything else so first of all i'm just going to add the login info so the login info must consist of an identifier and a password and the password is test1234 okay so first of all we need to login to our application how do we do that well we are going to do const we are of course going to access this route right here so it says auth local so we are logging in with fetch but here we need to set up some options for that login so first of all we need to log in with the post method so we do method next thing we need to send some headers and those headers are going to be accept application json and content type json after that we need to send our login info that we defined right here okay so we are sending all of this and after that i'm just going to set the login response to be equal to a weight login json okay so we set this up now i just want to show it in my component so i'm going to pass it here so that we can see it in the console and i'm going to send this login response as props to our component so we are just going to set this to be login response and also i wanna add it here so what is happening right here is because we are doing this is in get service side props once we refresh the page the page is going to try to log in into our strap backend so if i save this go here and refresh this page again now we are getting this status code uh forbidden but here we are getting undefined for some reason let me just check why that is i shouldn't call this login response but auth data okay save it try it again refresh it and now as you can see we are getting this status code forbidden still but one thing very important thing that we are getting is this right here so we are getting uh jbt this is json web token with which we can access our authenticated routes or our protected route so as you can see we are getting from our strip backing this token which is going to be very important to us and also we are getting a user uh which is test user and so on so this right here is super important for us to be able to get those posts because as you can see we are logged in but we are still not getting those posts because to get them we need to set uh we need to send this jvt token to our api endpoint uh for it to give us those posts or those articles so how do we get those articles well right here where we are fetching those articles we need to send some additional options and those options are also going to be headers and as you can see we are sending headers with which is called authorization and then you need to send this bearer and then you send loginlessresponse.jwt and that that should actually be it so if i save this go to our browser refresh it and now as you can see we are getting paid article number one paid article number two great so this is the way you would get those articles of course some of you when i show you this you already know what to do but for those of you who don't know what to do now we are going to create that login page we are going to set up logic of for the users to not be able to access our paid articles route until they are logged in so behind the scenes i cleaned up this paid articles.js as you can see now it's just a normal page so that we can have a clean slate going further so if we go to that page and click on paid articles you just get paid articles next i also created this login.js which is also just the normal page i'm importing style because we are going to need some styles to style our form we are of course importing public runtime config and that's about it and if you go to that page you go to login it will just say you need to login to access this page and that's about it so now we have those two pages next thing we need to do we need to add some logic that will say so if you have that jvt so that token then you can access paid articles page otherwise just go to the login page first of all we are just going to hard code it to show you how it works next when we do the login we are going to get that key and then we are going to implement that so first of all what you need to do is you need to import router right here so we are importing router from next router next thing i'm going to create a function right here which i just stole from the internet i think i didn't change it probably at all so this function is just going to redirect our user to the desired location and here i'm going to set a const to be jwt and i'm going to set it just to be false for now so now this is going to be hard coded but later we are going to get that key and do something with it and after that i'm just going to add a conditional which is going to say if you have jvt then go to the paid articles otherwise uh go to the login page we are saying this if there is no jwt then and the path name that you're trying to access so we are getting that from this context right here and the path name is you want to access is paid articles then please redirect the user to the login page so if this is false the user is going to go to the login page so let's see if this works so if i go right here and go to paid articles as you can see we go to the login page actually so let me show you again if i go here to next movies click paid articles instead of going to paid articles page now we are going to this page so this is our logic for setting up that login so that the user cannot access paid articles and also if i do paid articles i am again just going to go to the login page great so if we want to go to the uh to the paid our articles page we can now at least just set this to be true save it check it out in the browser now if i click on the paid articles i'm going to the paid articles great okay so next let's set up our login page okay so first of all let's add a form to this page that is going to consist of your username or your email actually and your password okay so as you can see we got input field of type email type password and we have a button for logging in and next thing i just want to make this form look just a little bit prettier so we are just going to add some styles in our login style so right here and save this check out the page so if we go to login you can see so this is going to be our username or actually our email and this is going to be our password of course none of this works right now because we didn't apply or implement any logic to this so of course it can't work next thing we want to do is we want to import use state from react because we want to use use state hook to control our the state for our component so you just do it like this and next we want to set that state up of course check out the previous episode if you don't episodes if you don't know what's going on here so we are using use state hook to set up username and password and also functions for setting those username and passwords up so we are going to have a set username and set password functions now we need to implement those on our input fields so for email we are going to say on change we are getting the event of this field and we are setting set username to be e dot target.value and the value is going to be username we do pretty much the same thing for password so on change we want to set the password we are going to take the value of this field and the value is going to be password and after that we wanna on click handle the login so when somebody clicks here we wanna handle that login for now i'm just going to create a function that is going to be called handle login so i just create this function handle login and when i click the button we are just going to get a login handled in our console so if i go right here refresh it just add anything right here click login login handled okay great now uh what we need to do is we actually need to add logic to handle login so that it will go to our server authenticate us and somehow save jwt into a cookie so that we can use it throughout the site okay so first of all we need to set this up to be async function because we are going to use fetch inside of it and we need this function to be async function to be able to use a weight next thing we want to do is we want to set up the login info just like we did at the beginning of the video and the login info in this case of course is not going to be hard coded but we are getting the username and the password that the user enters inside of our form after that we also do pretty much the same thing that we did before we wanna access our endpoint and get the jwt token from it when logging in we're just logging in the method post headers we get those headers and of course we send login info to the server and then we want to get the login response okay and now just to see if this works we can log out login response to see if we get that jwt token okay save this go to the browser refresh it and now if i do something like this as you will see you get the stat status code 400. the message is going to be uh out there identifier or password is invalid so this is the way that you can implement error handling inside your application we will not be doing that in this episode because this episode is going to be a very long anyway you can do that for your homework or where you are implementing this on production because as you will see this solution will not be hundred percent production ready one thing that you would have to handle yourself is of course this error handling uh maybe even uh front-end validation and so on okay so we aren't getting this uh we don't like that so let's refresh the page and try to log in with our actual data so for me that is test at test.com and the password is test1234 and now if i click login as you will see i am getting the jvt token and the user great now that we have that set up as i said before we need to save this dot jwt token inside of a cookie we unfortunately cannot do that in internal storage because this is an ssr application and you can't access local storage from your server and we will need that because we want to display our articles with using get server side props and as you know get server side props works only only on the server so we will need to save that cookie and we are going to use a plugin for nexjs called new keys which is going to handle all of that for us and we will be able to access the cookies on our server which we are going to be needing of course as i said we are going to be using nukis plugin this is the page this is the documentation which of course i urge you to read so as you can see you can get the cookies from ssr or client or you can get the cookies only on client and you can set the cookies and you can destroy the cookies and everything like that please read that documentation now we are just going to first of all install them uh on our application so you just do npm install nookies so once this is done we can go to our code editor and now we of course want to import nookies but we are not going to import all of it we are just going to import set cookie from nookies so we want to set the cookie to be that jwt token that we got and we are going to be doing it right here so you set the cookie very easily you get you go set cookies you do now because this is going to be running on the client so in the browser uh we you do jwt so this is going to be the name of our cookie and the value of the cookie is going to be login response dot jwt and that's about it now our cookie should be saved once we log into the application and after that we want to do something like this so we are just going to do router push paid articles so once all of this passes we want to push the user to the paid articles page of course if you have multiple pages you're going to have to handle this differently i'm going to hard-coded this for our example so uh okay let's save this and of course this this is not going to work right away because we don't we didn't import router from next actually from next router okay so now it's imported so that we don't get any errors save this let's just test this out again go to our login page refresh it okay click login nothing happens right now we did go to the paid articles because actually we shouldn't have gone to the beta articles just yet but we did go because in our app.js this is set to true if it was set to false we wouldn't be able to go to them but we are going to handle that in just a second but before that i just want to show you so if you go to application you go to cookies and you filter jwt and as you can see we have our cookie set up this is our cookie value great so we have that set up next thing we need to do we need to handle this uh like i just said so instead of this being true or false we need to get that cookie and if that cookie is okay then we wanna redirect the user to a paid articles page and if the cookie is not set up of course you're going to go to the login page okay so before we start setting all of this up i want to remove this cookie because now we have it so our paid articles route is always going to work so i'm just going to remove this so now we don't have that cookie set up let's go to our app.js file so in here first of all i want to import parse cookies from nookies because now we don't want to set the cookie but we want to read the cookie now we go down here and instead of jwt being just true we are going to actually parse the cookies from the context so this is the beautiful thing about nook is you can access cookies from client side from server side however you like you just use this context right here so we want to parse the cookies and we're going to set it up to be parse cookies we want to parse the context because there are going to be in our context and then we just do that jvt jwt and that's about it right so if i save this right now go to my page and try to go to paid articles we are just going to end up on a login page because remember we still don't have this cookie set up okay so now if i go test and click login i will go to the paid articles of course if i remove the cookie try to go to the paid articles i'm going to go to the login page again great let's login one more time and now we are on paid articles page of course now we need to display those cookies and since you always need that jwt you can't just display them however you you like you will need to use this token to access your articles since of course we are going to be needing the cookies i will just do parsnookies from nookies because of course we wanna parse the cookies after that we are going to set this get server side props to have.jwpt we are going to parse the cookies through context and you just do ctx right here so that we have our context and now just like we did at the beginning of the video we need to get our articles and of course we are getting them by using fetch and don't forget we need to send the header with authorization that we are getting from our strappy and we are sending this jwt token next thing we need to do we just need to get all the articles and send them us props to our component so you do articles await res.json and you want to send them right here okay of course to be able to access them we need to destructure this to be articles okay and now all it needs to be done we just need to display those articles and we are just going to map through them so we do articles map we just added div with class name of article the key is going to be the article id and then we just do article.title article.body and that's about it save this if we now go to our page uh we can't read the map of undefined okay let's just try to refresh it okay we just needed to refresh it because this is uh happening on the server side so we need to refresh this page and as you can see we are getting those articles as i said i'm not going to implement error handling and so on in this video and also i'm not going to implement logging out but for you to log out out of your strap back end all you need to do is you need to of course route the user to for example your home page and then you need to destroy this cookie and just check the documentation as you can see nook is destroy and you destroy that cookie name and that's how you log out the user however we are not going to be doing that you can do that for yourselves now if i just remove this let's just test it once again go to the front page we want to go to the paid articles but we can't so we get to the login page we do test click login and we are on our paid articles page so this is how you do authentication with nexjs and strappy just remember this is not 100 production ready you need to handle log out you need to handle errors you need to handle a form validation invalidated tokens and so on but this is a good starting point to create the login or user areas for your nexjs and strappy websites okay so this has been it for this video everything we did here will be available for you on github the link will be in the description below and as always thank you guys for watching and i will see you in the next one [Music] you
Info
Channel: Watch and Learn
Views: 33,726
Rating: undefined out of 5
Keywords: nextjs, next.js, strapi, javascript, authentication, JWT, tutorial
Id: U2rRxzjruKg
Channel Id: undefined
Length: 27min 8sec (1628 seconds)
Published: Sat Aug 29 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.