Тёмный

Custom Protected Route Component in React 

Cosden Solutions
Подписаться 110 тыс.
Просмотров 47 тыс.
50% 1

Опубликовано:

 

25 окт 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 133   
@ayberk272
@ayberk272 9 месяцев назад
Just today, needed a validation of my knowledge on protected routes. You came outta nowhere again. Thank you for the direct-to-the-point content!
@hoaxygen
@hoaxygen 5 месяцев назад
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!
@FarrukhKarimov
@FarrukhKarimov 8 месяцев назад
Love your videos dude! So clean, so straight forward, always informative! Keep up the great work!
@athena-alpha
@athena-alpha 8 месяцев назад
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
@Svene7
@Svene7 9 месяцев назад
The video production quality is top-tier.
@FS-yq9ef
@FS-yq9ef 8 месяцев назад
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', } ] } ];
@cosdensolutions
@cosdensolutions 8 месяцев назад
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?
@FS-yq9ef
@FS-yq9ef 8 месяцев назад
@@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.
@markosmk
@markosmk 4 месяца назад
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
@Lykkos-321
@Lykkos-321 9 месяцев назад
glad I'm subscribed to this channel!! thanks for all of this maan!!
@rjwhite4424
@rjwhite4424 9 месяцев назад
I've been doing mine different using react router's but I really like your method better.
@AdemBenAbdallah-t6h
@AdemBenAbdallah-t6h 9 месяцев назад
Best Channel that talk about react keep going
@sitrlax5536
@sitrlax5536 9 месяцев назад
I have been dwelling deep in the react ecosystem and you are my go to channel. Love from India 🇮🇳 ❤
@muhammademirsyah8037
@muhammademirsyah8037 9 месяцев назад
Love all of your content, keep it up!
@mrluckyuncle
@mrluckyuncle 9 месяцев назад
Coincidentally just what I was about to implement. Thanks 🙂
@Kay8B
@Kay8B 4 месяца назад
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.
@VINOTHKUMAR-ey1yg
@VINOTHKUMAR-ey1yg 7 месяцев назад
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..
@Pareshbpatel
@Pareshbpatel 4 месяца назад
React: Protected Route Component, so clearly explained. Thanks, Darius {2024-05-30}
@juliaof.kataleko7595
@juliaof.kataleko7595 4 месяца назад
Best teacher ever!!
@juanantoniovivaldy
@juanantoniovivaldy 9 месяцев назад
Why not using the in ProtectedRoute components?, and just put that component to wrap entire private route, i think doing that, have more fastest way
@lucasirondesouzacamargo1540
@lucasirondesouzacamargo1540 9 месяцев назад
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
@Js-Lovers
@Js-Lovers 8 месяцев назад
Your understanding is no, please try to learn well about outlet components.
@Priva_C
@Priva_C 4 месяца назад
⁠explain then genius @js-lovers
@nicolas_vl
@nicolas_vl 7 месяцев назад
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
@Anteater23
@Anteater23 2 месяца назад
Why does navigate need to be a dependency in the useEffect hook?
@UkrScript
@UkrScript 8 месяцев назад
Thank you, was very helpful
@ProdByGR
@ProdByGR 5 месяцев назад
This the best approach
@Admin-up4hh
@Admin-up4hh 6 месяцев назад
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
@asfandyar8088
@asfandyar8088 9 месяцев назад
Love ❤ all of your videos sir. Your videos very helpful.thank you so much. Keep it up.
@paleo3142
@paleo3142 3 месяца назад
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.
@johndevnoza4223
@johndevnoza4223 9 месяцев назад
Love your videos. And i would love to see your teachings for next js
@cosdensolutions
@cosdensolutions 9 месяцев назад
I'm still on client side React for now, will evaluate later on what direction to take but definitely could end up doing some for sure
@johndevnoza4223
@johndevnoza4223 9 месяцев назад
@@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
@cosdensolutions
@cosdensolutions 9 месяцев назад
Learn React first definitely! Then if you want go to nextjs, but you definitely need the React foundation
@johndevnoza4223
@johndevnoza4223 9 месяцев назад
@@cosdensolutions Thanks for the response
@Solo_playz
@Solo_playz 9 месяцев назад
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!
@abdulrhmanburqaa328
@abdulrhmanburqaa328 7 месяцев назад
Any update?
@endlessnameless3613
@endlessnameless3613 9 месяцев назад
Just what I need right now
@sadique_x_
@sadique_x_ 9 месяцев назад
funny how I'll come across a video made today on something I'll learning today
@kishoreramana1
@kishoreramana1 8 месяцев назад
If I am not wrong, ReactContext will be removed after page refresh, then how can we use context in that case ?
@MadDogg3669
@MadDogg3669 8 месяцев назад
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!
@gabrr.community
@gabrr.community 9 месяцев назад
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.
@electrpaleo
@electrpaleo 9 месяцев назад
You should use Outlet with children, so you can wrap all protected routes under a layout with the router
@belkocik
@belkocik 9 месяцев назад
Would love to see in this video :D
@cosdensolutions
@cosdensolutions 9 месяцев назад
yeah that would also work!
@JahangirKhan-t2p
@JahangirKhan-t2p 6 дней назад
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.
@foveromw
@foveromw 6 месяцев назад
Quick and simple ❤
@kalyaniingle8718
@kalyaniingle8718 6 месяцев назад
Awesome content💚💚
@ardianhotii
@ardianhotii 9 месяцев назад
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
@paleo3142
@paleo3142 3 месяца назад
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
@ardianhotii 3 месяца назад
@paleo3142 yeah thanks it would be great, is that repo pubilc so I can look at it or you have it private , I would like to have the setup you have
@paleo3142
@paleo3142 3 месяца назад
​ @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.
@ardianhotii
@ardianhotii 3 месяца назад
@@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
@paleo3142
@paleo3142 3 месяца назад
@@ardianhotii Good luck!
@saadniaxi1623
@saadniaxi1623 9 месяцев назад
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 😅
@aakashsingh3711
@aakashsingh3711 7 месяцев назад
Can you please make a whole playlist of tutorial on react router dom? You make things very easy.
@Jacek2048
@Jacek2048 17 дней назад
Great! Now I don't need any auth in my backend, I can just use React.
@romaghorjomeladze439
@romaghorjomeladze439 9 месяцев назад
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
@cosdensolutions
@cosdensolutions 9 месяцев назад
yeah fair point
@romaghorjomeladze439
@romaghorjomeladze439 9 месяцев назад
Thank you for such a great channel. I love it 💙💙
@usamaansari4231
@usamaansari4231 5 месяцев назад
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?
@heech6941
@heech6941 Месяц назад
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
@royerrrrutti9903
@royerrrrutti9903 2 месяца назад
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...
@brNoMundo123
@brNoMundo123 9 месяцев назад
Conteúdo incrível 👏👏👏👏
@gamechallengecategory5974
@gamechallengecategory5974 7 месяцев назад
carai brasileiro ta em todo lugar kkk
@osamakaram3942
@osamakaram3942 6 месяцев назад
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.
@AkshayParkad
@AkshayParkad 9 месяцев назад
wrap {children } in div or react fragment at the time of return {children}..otherwise it may cause a problem in some cases
@fedeabj
@fedeabj 9 месяцев назад
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
@paleo3142
@paleo3142 3 месяца назад
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.
@ericng3673
@ericng3673 6 месяцев назад
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
@cosdensolutions
@cosdensolutions 6 месяцев назад
You let the user state redirect. When user state changes, redirect. No race condition 😁
@gabru4477
@gabru4477 9 месяцев назад
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?
@adarsh_malviya
@adarsh_malviya 9 месяцев назад
I also want to know that
@cosdensolutions
@cosdensolutions 9 месяцев назад
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
@juanantoniovivaldy
@juanantoniovivaldy 9 месяцев назад
I think role_id is needed for doing that, so u can make some logic to navigate the user by his role to the right portal routes
@gabru4477
@gabru4477 9 месяцев назад
@@juanantoniovivaldy i am getting roles from my login api but i think that is not a good approach i need something different
@gabru4477
@gabru4477 9 месяцев назад
@@cosdensolutions i added roles in protected routes admin for admin routes likewise parent and teacher but that logic is not a good approach i think
@jinshin.19
@jinshin.19 6 месяцев назад
Hi to use this I have to do this right? { path: "/", element: ( ), }, { path: "/read/:id", element: ( ), }, { path: "/update/:id", element: ( ), },
@abdhelal
@abdhelal 9 месяцев назад
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 😊
@cosdensolutions
@cosdensolutions 9 месяцев назад
show a loading spinner until you get a user
@RitikRaj-we2sc
@RitikRaj-we2sc 8 месяцев назад
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.
@lucasirondesouzacamargo1540
@lucasirondesouzacamargo1540 9 месяцев назад
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.
@cosdensolutions
@cosdensolutions 9 месяцев назад
fair point, would work!
@belkocik
@belkocik 9 месяцев назад
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​
@ThanHtutZaw3
@ThanHtutZaw3 9 месяцев назад
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 ?
@jeandedieuiradukunda6079
@jeandedieuiradukunda6079 3 месяца назад
you're amazing
@TanNguyen-lj4zp
@TanNguyen-lj4zp 4 месяца назад
Can you show me what extensions you are using?
@lucasmachado6447
@lucasmachado6447 9 месяцев назад
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?
@cosdensolutions
@cosdensolutions 9 месяцев назад
nope, might actually be better because you can do it without an extra render
@mfion1
@mfion1 9 месяцев назад
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!
@dsilver1330
@dsilver1330 9 месяцев назад
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?
@cosdensolutions
@cosdensolutions 9 месяцев назад
both are fine! Mern might be more versatile though
@fahiyejr1930
@fahiyejr1930 5 месяцев назад
How do I make my login page seperate, please help??
@bizmich_
@bizmich_ 6 месяцев назад
how to protect /sign-in after when i signed-in?
@abhinasregmi9742
@abhinasregmi9742 8 месяцев назад
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?
@cosdensolutions
@cosdensolutions 8 месяцев назад
You can, but this was an example. Your isSignedIn should come from the backend
@abhinasregmi9742
@abhinasregmi9742 8 месяцев назад
@@cosdensolutions ok thanks for the help
@HariharanArjunan-i1k
@HariharanArjunan-i1k 8 месяцев назад
please teach about how to add common header file in createBrowerRouter technique
@youssefkhaled2113
@youssefkhaled2113 9 месяцев назад
can i do the same using a layout and add my routes under this layout that does the same protection logic ?
@cosdensolutions
@cosdensolutions 9 месяцев назад
yeah
@Ganievs09
@Ganievs09 9 месяцев назад
What if we want several routes to be protected? Should we Wrap all Components in ProtectedRoute Component or there is better way?
@cosdensolutions
@cosdensolutions 9 месяцев назад
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
@Ganievs09
@Ganievs09 9 месяцев назад
Yeah I got what you mean. That's good approach. Thanks for your cutting edge videos.@@cosdensolutions
@capt_vj
@capt_vj 8 месяцев назад
is this a higher order component? the ProtectedRoute?
@cosdensolutions
@cosdensolutions 8 месяцев назад
yeah
@iury664
@iury664 9 месяцев назад
this way of import, import * as React from react isn't make the app be more weight?
@MohamedElguarir
@MohamedElguarir 9 месяцев назад
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.
@iury664
@iury664 9 месяцев назад
@@MohamedElguarir thanks
@megafirestar5030
@megafirestar5030 9 месяцев назад
how to get that user i mean can you tell us the best practices for handling auth in react?
@juanantoniovivaldy
@juanantoniovivaldy 9 месяцев назад
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 🙏
@cosdensolutions
@cosdensolutions 9 месяцев назад
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)
@ignacioarriagadairiarte4338
@ignacioarriagadairiarte4338 9 месяцев назад
nice video
@tamaniphiri
@tamaniphiri 9 месяцев назад
Solutions for modern day problems, great stuff🚀💯
@chukwukaeze4736
@chukwukaeze4736 3 месяца назад
Why is bro recording in dark theme
@davidhusted817
@davidhusted817 9 месяцев назад
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 😊
@qureshiowais6951
@qureshiowais6951 7 месяцев назад
why not keep it !user because it seem better as if any false will get back to sign in page!!!
@UFO_808
@UFO_808 9 месяцев назад
Bro where are you from, if it's not a secret? 😀
@cosdensolutions
@cosdensolutions 9 месяцев назад
Originally from Romania
@UFO_808
@UFO_808 9 месяцев назад
@@cosdensolutions Lol I'm from Serbia bro, I wisited Timișoara last winter 😄
@cosdensolutions
@cosdensolutions 9 месяцев назад
I live in serbia atm hahaha, serbian gf
@UFO_808
@UFO_808 8 месяцев назад
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? 😄
@VvazoLsky
@VvazoLsky 7 месяцев назад
omagad , this is tutorial wish me search
@amitrana3053
@amitrana3053 9 месяцев назад
Osm learning
@deepaksurya9742
@deepaksurya9742 9 месяцев назад
Start NextJs
@tanmay4l
@tanmay4l 9 месяцев назад
Custom hooks
@phamtienthinh1795
@phamtienthinh1795 7 месяцев назад
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
@phamtienthinh1795
@phamtienthinh1795 7 месяцев назад
Which is the most important part
@lokeshkaushik1812
@lokeshkaushik1812 9 месяцев назад
First
@cosdensolutions
@cosdensolutions 9 месяцев назад
Congrats!
Далее
The Most Important Design Pattern in React
35:04
Просмотров 88 тыс.
진 (Jin) 'I'll Be There' Official MV
03:15
Просмотров 7 млн
Zustand with Context API - An Advanced Pattern
19:12
Authentication Flow in Next.js (Complete Tutorial)
30:37
Refactoring a React component - Design Patterns
15:19
React protected routes in 4 minutes
4:03
Просмотров 18 тыс.
How To Debug React Apps Like A Senior Developer
21:07
Просмотров 156 тыс.
You might not need useEffect() ...
21:45
Просмотров 167 тыс.
React visually explained: 'use client'
15:57
Просмотров 55 тыс.
Why does JavaScript's fetch make me wait TWICE?
6:23
Просмотров 193 тыс.
Modern Data Fetching in React (Complete Guide)
16:41
Просмотров 59 тыс.