How to create Protected Routes and Authentication with React Router V6 2023

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
being able to create private pages is a big part of many applications and websites there are lots of different ways to achieve this but what I want to do is show you the foundation for all my applications which I think is one of the fastest and most robust ways to get started as with all my videos from now on a GitHub link to the finished application is in the description the font size should be large enough for you to see which helps and I'll not be typing along and building this from scratch instead because all of the code is available for you to download I'll be talking through what it's doing and why any questions you have leave them in the comments section and I'll aim to reply to everyone as quickly as I can anyway let's get into it so let's start with the end product and work backwards and I'll go as slow as I can to try and explain everything that's happening so here we have a basic website or application with a header some menu options and then outputting a component based on the current route so we have home at about which switches between the home and the boat components and then the login page which if we enter a username and password and hit login will give us access to some private routes or non-public routes and we have one route called private which shows a member's area component and then we have an account component which was previously hidden and that's showing the current username of the person logged in we then also have a log out button which if we click the authenticates the user and only allows them to access these pages if for example we directly try and access the account page we're just shown nothing because the the user is not authenticated so let's have a look at the code behind and walk through exactly what's happening so the first thing to note is the app.js file is importing react router and also this auth wrapper which I've created and we'll walk through that shortly and it's simply outputting browser router to give the child components access to react router and then everything is being controlled by our auth wrapper which is what decides what the person on the application or website can and cannot see so if we go into the auth folder and have a look at this auth wrapper you'll see that we're importing create context use context and use State we're importing the header components and we're also importing the menu and routes which will step through next we're creating our own context which if you don't know about the use context hook I suggest you go and check out one of my other videos when I go into detail about the use context hook or just Google it it's really really useful and saves you having to pass stateful items down through your child components we then export auth data which is a constant of the context that we've created and then our main wrapper has a stateful item of user and step set user which by default is an empty string for the name of the user and is authenticated false again this is a really basic version of private root and authentication you would normally store a lot more information on the user in here we have a login function which takes the username and password and decides whether the user has entered the correct password and normally you would make an API call to your back end which would decide whether the username is a match and the passwords are match but we're just hard coding and returning a new promise that if the password entered is equal to password then update the user in the state with the username that was entered and is authenticated true and we're resolving success if the password entered is not password then we're rejecting it with an error message of incorrect password next is the logout function which is simply setting the is authenticated to false so we're logging the user out and they can no longer access the private routes and the auth wrapper is then returning our auth context so it's making available the user item in the state the login function and the logout function available to the child components and then we're simply rendering the header the menu and The Roots and the route shown will depend on the path in the browser so let's have a quick look at this header menu and routes components we go into components and then structure the header is a very simple component just outputting some HTML the navigation is exporting an array of objects so instead of defining my paths directly in a paths file or in the output I'm dynamically creating them and I'll cover that next but I'm dynamically creating them depending on whatever's put in this object the reason I do that is because it's much simpler especially considering that we're using this navigation object to run the menu and the available routes to the user to just have to Define them once so we've got the Home Path which is true for the menu and is false for private so we're saying it can always be shown in the menu and it's not a private route I.E it's public the same with the about path so we're defining the path the name for the menu the element that will be shown once react router matches that path is menu true is private false we then have the login path which you'll notice is is menu false and that's because we want to hard code whether login should be shown or not depending on whether the user is authenticated but again it's a public group so it's private false and then we have our two private routes which are private and the count so yes they can show in the menu depending on whether the user is authenticated obviously and is private true so these routes will never render unless the user is authenticated we're just quickly walk you through the pages which are just simple components so about account which is pulling in auth data from our auth wrapper and giving this component access to the user state in order to display the name the home component very basic the login is outputting a forum for the user to enter their username and password updating the local state item here Forum data using the user reducer as opposed to use state again if you're not sure about use reducer I've got a video on that if you want to subscribe to the channel and search for the use reducer hook or or alternatively just search Google fairly straightforward but can save you a ton of time and then we've got the do login once the button is clicked which is here and do login is literally just calling the login function from our auth wrapper again that's being imported here passing through the username that was entered in the form and the password and as long as there's no um uh rejection by that promise then it will navigate to the forward slash account page if there is a rejection and if you remember in our oauth component or author wrapper if we don't match we're rejecting with incorrect password then we set error message as to whatever was whatever error was passed back so that's the login page and then the private route is just a simple private members area we then have the render navigation page which is a little more complicated so that's importing this array of objects from the navigation file and it's doing a render root so this is where we're dynamically creating the routes that are available to the user now again you could just output all of the routes in your auth wrapper but if you did that if the user wasn't authenticated and happened to know the URL forward slash account or forward slash private they could then potentially get access to that route so we're mapping through the navigation object or array of objects and saying if it's private and the user is authenticated then that's fine we can give them access to that route else as long as it's a public group I.E not a private route then that's fine as well we can output that route so this render Roots is what's deciding the paths and routes the user has access to depending on whether they're authenticated or not and whether the route has been defined as private or not we then have a render menu component which is making use of the user State item and the logout function that we defined in our wrapper and it's importing that from auth data this menu item is just defining what a menu item looks like and then the real work is here so again we're mapping through the navigation items and we're saying if it's public I.E not private and is menu if you remember inside of our navigation item we're defining whether something should be shown in the menu or not so if it's public and it's meant to be in the menu that's fine it can be shown else if the user's authenticated I.E if it's not public if the user is authenticated and it's meant to be in the menu that's fine show a menu item for that as well and then if you remember in the navigation items I said that we didn't want to have the login by default in the menu what we've done here is to hard code if the user is authenticated then show them the logout button and that simply calls the logout function that we're pulling through from our auth wrapper else if the user is not authenticated show them the login link and so if we flick back to the application hopefully that will make a bit more sense about what's going on if I enter password incorrectly we'll get incorrect password if I enter it correctly will be logged in and we then have access access to these routes so adding new components to this app because there's probably going to be lots of private components you want to give the user access to or we would simply need to do excuse me is create a new component um it may be order history for example and then inside of the navigation object of arrays array of objects sorry all we would need to do is add in a new object here call it forward slash order history name order history pull through the element we've just created decide whether it should be shown in the menu probably true and decide if it's private true or false and you can therefore very quickly add as many public and private routes as you like the one other thing to mention that I've not covered here is that inside of the auth wrapper you'll notice that we're deciding um what to show the user based on whether they're authenticated or not and that's being pulled from the state if we were to hard refresh the page if I do Ctrl R you'll notice we're logged in log back in that's fine but a refresh again we're logged out now obviously a lot of the time the pages don't refresh because we're using react router to navigate through the different routes and components but users ultimately do refresh the pages especially if they feel like something's taking too long or they're stuck in which case you would need to implement some kind of local storage um inside of this app now I would normally store things like a user key and um a timestamp for when the session should expire to determine whether the user is logged in or not and depending on things the user does throughout the app I may refresh that timestamp so they don't automatically get kicked out I'm not going to cover that in this tutorial but if you'd like to see an implementation of that please let me know in the comments and if there's enough demand I'll be sure to record a video so that's it a simple but effective way to manage authentication and private routes in react I hope you've enjoyed this video again a link to the GitHub repository is in the description so go ahead and download that and I'll see you in the next one
Info
Channel: Kodie
Views: 55,556
Rating: undefined out of 5
Keywords: react router, react router dom, react, private routes, react routers, react router v6, react router v6 tutorial, react authentication, react router tutorial
Id: q94v5AhgrW4
Channel Id: undefined
Length: 14min 8sec (848 seconds)
Published: Wed May 17 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.