React Router Tutorial - 15 - Authentication and Protected Routes

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
all right for the final video in this series let's learn how to handle authentication with react router when building web applications you'll come across the need to protect some routes in the app from users who are not logged in for example in an e-commerce site the products page might be publicly accessible whereas the profile page or the order history page requires that a user be logged in the react router itself does not have a feature to protect routes but you can implement the functionality without much difficulty in this video let's see how to protect routes using react router and the context api from react first let me go over the scenario we will be implementing in our app we are going to add a new link in the navbar which should take you to the profile page but the profile page is a protected route if you are not logged in you'll be redirected to the login page you can enter a username and click the login button you will then be able to view the profile page which displays the logged in username you also have a logo button on click of which you'll be navigated back to the home page pretty simple scenario as you can see let's head back to vs code and understand how to implement this now there is quite a bit of code we have to write and understand so let's take this one small step at a time step one let's create the profile page add the link in the nav bar and configure the corresponding route in the components folder create a new file called profile.js within the file create a simple that says profile page in the nav bar add a new link to slash profile so copy the nav link paste it and change slash profile the link is also profile in app.js configure the new route so route path is equal to profile and element is equal to the profile component make sure to import the component at the top let's save the file and test to see if this works click on profile and we have the profile page step 1 is complete but we know this route should be a protected route and accessible only if the user is logged in so for step 2 we need to implement the functionality to figure out if the user is logged in or not to keep it simple we're going to maintain a user state variable and provide it to the entire component tree using react context so back in vs code in the components folder create a new file called auth.js this file perhaps belongs in a separate utils folder but i'm going to leave this in the components folder for now within the file we're going to create an auth context so at the top import create context from react next const auth context is equal to create context the initial value is going to be null next we're going to define the auth provider component so export const auth provider this is equal to an arrow function and within this component we maintain the user state and define the functions to log in and log out begin by importing you state from react next create the state variable let's call the variable user the function set user and the initial value is null now use this setup function to define log in and log out functions so const login receives user and we're going to call set user passing in user similarly const logout doesn't receive any arguments we're going to call set user passing in null now we're going to provide these values using the auth context provider so return auth context dot provider and this is going to wrap the children props the provider component needs a value prop and this is going to be equal to an object with the same key value pairs user login and log out make sure to restructure the children props finally we're going to define a function that returns the value of auth context so export const use auth is equal to a function where we return use context passing in auth context make sure to import use context hook at the top all right now that we have the auth context provider in app.js we wrap the entire component tree with odd provider make sure to import the component at the top all right we now have access to user login and logout functions throughout our application which means we can now proceed with step 3. for step 3 let's implement a login route in the components folder create a new file called login.js within the file create a simple component now this component needs to accept a username so import you state at the top and create a new state variable user the function is set user and the initial value is an empty string this state variable should be tied to an input element so label username is going to be an input element type is equal to text and on change we get hold of the event and called set user passing in event dot target dot value next add a login button so button the text is going to be login and on click of this button let's assign a function called handle login let's define the function so const handle login is equal to arrow function and within the function we need to call the login function from auth context for that call use auth which is to be imported from the auth file and assign the return value to a constant called auth this should in fact be outside handle login within handle login call auth.login passing in the username once we set the username we navigate the user to the home page for that we use the use navigate hook so at the top import use navigate from react router dom and within the component const navigate is equal to use navigate and then within handle login navigate to the root finally add a login button in nav bar the button should only be shown if the user is not logged in so once again get hold of the auth context so const auth is equal to use auth and make sure to input it at the top then in the jsx curly braces if not auth.user so if the user is not logged in render a link so nav link and this should be to the login route and the text is also login once we have the new link let's configure the route so make a copy of this path is going to be login and element is going to be the login component make sure to import the component at the top so step three is complete for step 4 let's display the logged in username in the profile component and also add a logout button to display the username we once again rely on authcontext so const auth is equal to use auth and make sure to import it at the top import use auth from the auth file within the jsx welcome auth dot user and now to log out let's add a button it's a button the text is going to be log out and on click let's assign a function called handle logout let's define this function const handle logout is equal to an arrow function and within the function call auth.logout after logging out we redirect the user to the home page so again at the top import use navigate from react router dom call the hook and within the function body navigate to the root with that we have completed the login and log out feature for our application let's head to the browser and ensure it is working as expected click on login and we are at the login route enter vishwas and click the login button we are navigated to the home page click on profile and we see welcome vishwas click on logout and we are back at the home page everything is perfect except of course for the most important bit in this video which is that profile is still not protected so first step number five let's protect this profile route now protecting a route should be a reusable piece of code at the moment we just have to protect the profile page but we might have more protected pages in the future so we're going to create a reusable wrapper component that decides if the component can be rendered or if the user has to log in first in the components folder create a new file called require auth.js within the file create a component within the component get hold of the auth context so const auth is equal to use auth make sure to import it at the top now we check if the user is not logged in so if not auth.user and if this is the case we redirect the user to the login route and we do that using the navigate component from react router so at the top import navigate from react router dom and within the if block we're going to return the navigate component with a to prop is equal to slash login so back to the login route if the user is logged in however we're going to return the children prop so destructure it and return children now all we have to do is in app.js wrap the profile component with require auth so in the element prop require auth is going to wrap the profile component make sure to import require auth at the top let's now head back to the browser refresh and we are currently not logged in click on profile and you can see we are redirected to the login route login and we are on the home page click on profile and we can now see the profile page log out and we are redirected to the home page our protected route is working as expected now although this works great there is room for improvement if we log in and click the back button we are at the login page again to fix this in login.js on the navigate function add a second argument replace set to true if we now refresh login and click the back button we don't see the login route anymore another improvement we can do is redirecting the user back to the protected route after the login right now i click profile and login you can see that i'm at the home page it would be nice if i was back at the profile page for that we're going to work with state when navigating in require auth component at the top import use location from react router within the component call the hook const location is equal to use location next on the navigate component pass in the state prop state and we pass in an object with a key called path which is equal to location dot path name we can make use of this state in the login component at the top import use location again and invoke the hook const location is equal to use location next check if the path is set on the state object and use the same as the redirect path so const redirect path is equal to location dot state and if it is set access the path if not navigate to the root pass in redirect path to navigate let's test this now refresh click on profile log in we are back at profile log out and we are directed to the home page authentication and protected routes with react router has been successfully implemented and there's a lot to understand here so let me summarize the steps first we created the profile route which should be protected next we implemented the functionality to log in and log out a user for that we relied on react context and provided the context value to the entire componentry after that we implemented the login page we used the odd context to sign in and the navigate function to redirect in the profile page we used the same auth context to display the logged in user and handle the logout button finally we created the require auth component that checks if the user is logged in or not if the user is not logged in it redirects to the login route the user is logged in it renders the children prop we wrap any component that needs to be protected with the required component and this is done when we configure the particular route last but not the least we used replace to prevent the user from viewing the login page after logging in and a bit of use location magic to keep track of the redirection so this is pretty much how you handle authentication with react router with that we come to the end of the series on react router i promised i would create the series when version 6 is out and hopefully i haven't disappointed anyone if you found the series helpful please do leave a like and subscribe to the channel it really does help out a lot as always thank you for watching and until next time take care
Info
Channel: Codevolution
Views: 142,186
Rating: undefined out of 5
Keywords: Codevolution, React Router, React Router Tutorial, React Router Tutorial for Beginners, React Router for Beginners, Authentication and Protected Routes, Authenticated and Protected Routes in React Router, React Router Authentication, React Router Protected Routes, Protected Routes, Authentication
Id: X8eAbu1RWZ4
Channel Id: undefined
Length: 19min 45sec (1185 seconds)
Published: Wed Jan 26 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.