Wow, I came here looking for anything that I had missed and this turned out to be exactly like the code I came up with. That's a nice boost in confidence!
The problem of this is that it will flicker sometimes because useEffect will fired after the component render, the best way is to use the Navigate Component and check if it's signin
i set it up a bit differently, feel free to give some criticism if you think it is problematic. I create a layout that has a guard inside and then automatically all the children will be guarded as well because it depends on the parent. with this you can split your routes in seperate files as well. This will also not interfere if you have 2 layouts under root '/' because the protected routes are direct children of the layout import { Outlet, Navigate } from 'react-router-dom'; export function GuardedLayout() { const isAuthenticated = false; if (!isAuthenticated) { return ; } return ( Guarded Layout ); }; export const protected_routes: RouteObject[] = [ { path: '/', element: , children: [ { element: , path: '/private', } ] } ];
I get what you did, and it does work, but I don't like it. Child routes are not meant to be used as protected routes. They have different use cases and this way is harder to understand what is going on. Also, what would happen if you actually need a child route that's not protected? Or if you need to do more customisation?
@@cosdensolutions well if you don't need it to be protected it would go under a different layout that doesn't have the validation. With this we can set rules for each layout on a top level.
Other option is use property loader, (but without property action) then you can checking if user is authenticated, if user is not authenticated, you can redirect to login page, the difference is that you can’t use Navigate or useNavigate, but can use redirect(“/login”) from api of react-user-dom, I think it’s most simple, but your logic with layouts I think is good. And I used too, other option is directly control redirect in AuthProvider, but separe logic of routes in a custom object is the best, because you can check if some page need some specific role from current user, in a app in production, we used a custom object, then all routes is more control, and is more simple fix it if there are errors
I think you can improve this by implementing the outlet inside the protected route and just placing all the protected routes in the children prop in the browser router.
We don't blindly return children prop directly in ProductedRoute component , we should return the children prop if the user is already authenticated otherwise we should return null... During the mounting phase, the Homepage is trying to access the user object cause Error could happen because the effect is run after the mount... Hope this is correct..
The Outlet component helps you render content that is shared between different child routes. The examples has no shered content, so no need to use Outlet. But in a more complex case, sure, use Outlet where it fits
This approach is good for static pages but with loaders it won’t work. Loaders run before the element mount so even if you redirect an http request would be dispatched. With loaders we can implement something like a loader middleware that checks auth, roles and so on and then return a normal react router redirect to redirect the page in a react router way
Hi Sir, just found our your channel and as a react js developer I find your videos very informative. Thank you for all the efforts, just a request, can we get a video on light and dark mode implementation in our react app Thank your
Very well made video, but I think most people watching this should first ask themselves if this actually makes sense to use in their application. When it comes to protected routes, auth validation, etc I personally don't think this should ever be handled client side as shown in the video, because you should protect your routes before it gets served to the client; and then work with "protected" components for more granular protection that might be related to show elements based on a user's plan features, role, etc.
@@cosdensolutions well maybe i started to early to learn nextjs? Do u recomend that? Well im junior just learning everything and to be honest, when it comes to auth or any backend side then i hate coding. I just wanna learn enough to start working anywhere so then i can grow with real life concepts
Thanks for the awesome kinds of stuff! Could you please also create a video on how to create a proptected route for multiple routes may be 7-10 routes and how to handle code scalability using the component in react? Thank you in advance!
Please make a video where you demonstrate how to render a navbar with different routes based if user is logged in or not. And if is already logged in how to prevent him on hitting login route again! Thank you!
amazing! However if user is being changed somehow, importing it already cause the component to be mounted thus we don't need to add another useEffect. The less useEffect the better the performance will be.
this is the best tutorial I have ever seen for free.... good job brother I have one question how do we use this "isSignedIn" variable or how do we pass the data into it? I'm just confused in this part.
I would like to have a "standard" starter template to have auth logic like this ready to go. It's simple but when creating multiple projects and setting this up every time is unnecessary and time consuming I think . Very nice video and explanation in every step keep going
Just do it correctly once and you won't have to do it again. You can create a new repository called 'Project', and build it in a dynamic way so that it doesn't tie to any specific product. I did just this, and then have a Bash script that I run to launch a new app, which will create the new repository, modify any of the files using the new app name, deploy a database in a docker container and get everything ready to deploy. It literally takes 10 seconds for you to deploy a brand new app, with database, that you can immediately sign up for. And if you want to update something, go to your template repo, and make the changes there, so that all new apps will base it of that.
@ardianhotii I am open to discuss selling it if you're interested. I wouldn't usually do this, and I have tons of free public NPM libraries and repos of tools that we commonly use, but this Template has taken quite some time to perfection, and has been through 2 live products already. It just seems crazy to give it away for free without having the benefits of open sourcing it, considering all the time we put in it and that it includes literally everything to launch a new app. But this is also something you can do, it will just take you some time, and you'll have to prioritize clean modular code and ensure non of the components are too tightly related to any specific product.
@@paleo3142 I know I believe that putting the hard work for free sometimes its not worth it , but I'm not interested to buy thanks I appreciate it , I'm trying now to make my own nextjs (template - starter-kit) so I don't have to install all the same things over and over again for each project that's so time consuming and I feel you what you have been through because its not that easy to setup a big reusable project
Q1: why didn't we used the loader function? In real application, context is fetch from backend. We can check are redirect in loader function right? Q2: if I use this new method of createBrowserRouter, what's the best way to fetch context API? Loader runs too much 😅
it's great content only thing is that maybe it would be better to include asynchronous authentication logic as well to have loading state too. it will change your HOC a bit
I am working on a medical application to generate pdf. I am using firebase auth the problem is i am redirecting to "/user" If there is any user. But due to protected route i am unable to open other protrcted pages of application. As protected layout always send me to "/user". How can i solve this?
Hello do you have any idea why mine flickers the protected page for milliseconds and then navigate me back to the home page? It's working properly but the problem is it flickers the authpage
I am trying to apply the validations from the loader since this way it is obviously functional but I use the loaders to load data, I use it with the tanstackquery library and well when the user is no longer authenticated what happens is that first it makes all the requests from the loaders which obviously fail and at the end it makes the one that validates that we have a user to protect the route...
great 🖤. but make the check in the useEffect will work in the next render cycle and the children will be rendered before the check . is there is anyway to do the check before rendering any child -- if you console log any statement in the protected route it will work and then redirect to the login if the user is not auth.
Is this the best way to "fully" protect routes based on roles and permissions in react? I have a nextjs frontend with a laravel backend and Im trying to make the auth work in server components (*just* for this, to check if a user has a role before showing any content). Since Im not being able to make it work because laravel sanctum (the auth im using) works with cookies and I just cant make it work, I was thinking of simply using react. Thanks
I believe that you should always handle core route protection at the server level.You can use Next middleware or use your layouts as long as they are server components.
This doesn't tell the full story. Here's the usual bug that you will encounter First, sign in in the sign page, there is usually a button with onClick to set the state to user context, then navigate to a protected route. The problem here is the race condition. How can you ensure the user state is set b4 you navigate to the ProtectedRoute? After all, state updates are all asynchronous. More than often, the state is not updated, and the user is directed to the protected route which brings them back to the sign in page again b4 the user is set. The same but the opposite happens for logout. Similarly, wasn't covered
Can you tell me how can i protect the three portals route i mean i have parent admin and teacher portal i need to make them protected based on token of different login how do i make these routes protected?
At that point, you could consider those two separate "apps", so you could make two components for each set of routes. Otherwise, you could add some logic in your auth provider or equivalent that sets the login state of each
In a real application, the user is retrieved from a server, so initially, it will not be set (null). Therefore, in this scenario, redirection will occur before the fetch is settled. How would you solve this problem thank you 😊
If we have a loader function attached to the route, then how would we protect it ? If I use this logic then even though it redirects to the signin page still the loader would have made the network request already.
I think I woudl approach this a little differently, instead of having a ProtectedRoute component, I would have created a custom hook useProtectedRoute. The difference here is that the component that requires protection would be resposible for protecting itself by calling useProtectedRoute.
Will you make a video how to create a custom hook: useProtectedRoute? In addition, you may bring Outlet Component from React Router on the floor and show how to use it in this case- @electrpaleo `You should use Outlet with children, so you can wrap all protected routes under a layout with the router`@@cosdensolutions
what about next.js protected route ? I mean I can use useEffect but , I would like to know best practice because it is displaying flash screen of protect page . Is middleware need ? Or SSR cookie check in SSR page ?
Is there any difference in terms of behavior if instead of calling the navigate() function inside useEffect, I simply return inside an if statement in the component body?
I appreciate the informative content. Could you please create a video tutorial on integrating NextAuth.js with an Express backend? I'm specifically interested in a setup where the access_token and refresh_token are returned in the JSON response but not stored in cookies. Additionally, I'd like to see how the frontend can make server-side requests to the backend using the access token for authentication, with Axios. Thank you!
hi man! I just wanna ask, I want to freelancing web apps, I've learnt and understand html, css, js, react, tailwind, git. should I learn nextjs or mern?
Is it possible for user to change the isSignedin from the browser i mean like we can change state values in react components from inspect. If yes how to prevent that?
yeah you can wrap all of them, or what I do is I create an array of all of my routes, specify which ones are protected or not, and just map over the array and wrap the element so it applies to all of them (and then pass isProtected) boolean to the ProtectedRoute component
not really because when creating a production build the bundler you're using vite for instance does a lot of tree-shaking and optimizations, so any imports you're not actually using on your code get eliminated.
i need to know this too, i mean there is a lot of video in youtube about a authentication, but i need more advanced like handle role permission route for each user, handle if the token is expired, and so on 🙏
will eventually make a video, but before then I'm actually building a course that will implement a complete authentication like this in great detail so you'll have everything you need (and more)
We can summarize the logic of custom hook by using the nullish coalescing , I suggest this solution to make learners more deeply understand the logic operator in js 😊
Omg bro I cannot believe this.. 😂I can hear that you have a slight European accent so i thought maybe you are from Poland or Ukraine or something but I would never guess that u are Romanian living in my home country! 😂 Your videos have helped me with react, especially the one "useEffect - Simply explained", I was struggling with that one lol. How do you like it here, have you learned some Serbian phrases? 😄
This type of video kind drives me crazy, because it's REALLY helpful but fk useless at the same time U just show how to "block" a website but what about how to update the context and make us available to access to the route