Custom Protected Route Component in React

Поділитися
Вставка
  • Опубліковано 16 січ 2025

КОМЕНТАРІ • 134

  • @ayberk272
    @ayberk272 11 місяців тому +6

    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 8 місяців тому +1

    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 11 місяців тому +1

    Love your videos dude! So clean, so straight forward, always informative! Keep up the great work!

  • @athena-alpha
    @athena-alpha 11 місяців тому +11

    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 11 місяців тому +2

    The video production quality is top-tier.

  • @Lykkos-321
    @Lykkos-321 11 місяців тому +1

    glad I'm subscribed to this channel!! thanks for all of this maan!!

  • @Kay8B
    @Kay8B 7 місяців тому +2

    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.

  • @Anteater23
    @Anteater23 5 місяців тому +3

    Why does navigate need to be a dependency in the useEffect hook?

  • @mrluckyuncle
    @mrluckyuncle 11 місяців тому

    Coincidentally just what I was about to implement. Thanks 🙂

  • @FS-yq9ef
    @FS-yq9ef 11 місяців тому +3

    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  11 місяців тому +1

      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 11 місяців тому

      @@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 7 місяців тому

      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

  • @sitrlax5536
    @sitrlax5536 11 місяців тому +2

    I have been dwelling deep in the react ecosystem and you are my go to channel. Love from India 🇮🇳 ❤

  • @rjwhite4424
    @rjwhite4424 11 місяців тому +1

    I've been doing mine different using react router's but I really like your method better.

  • @asfandyar8088
    @asfandyar8088 11 місяців тому

    Love ❤ all of your videos sir. Your videos very helpful.thank you so much. Keep it up.

  • @Admin-up4hh
    @Admin-up4hh 9 місяців тому +1

    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

  • @electrpaleo
    @electrpaleo 11 місяців тому +2

    You should use Outlet with children, so you can wrap all protected routes under a layout with the router

    • @belkocik
      @belkocik 11 місяців тому

      Would love to see in this video :D

    • @cosdensolutions
      @cosdensolutions  11 місяців тому

      yeah that would also work!

  • @juanantoniovivaldy
    @juanantoniovivaldy 11 місяців тому +20

    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 11 місяців тому +8

      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 11 місяців тому +1

      Your understanding is no, please try to learn well about outlet components.

    • @Priva_C
      @Priva_C 6 місяців тому +2

      ⁠explain then genius @js-lovers

  • @Solo_playz
    @Solo_playz 11 місяців тому +2

    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!

  • @kishoreramana1
    @kishoreramana1 11 місяців тому +1

    If I am not wrong, ReactContext will be removed after page refresh, then how can we use context in that case ?

  • @muhammademirsyah8037
    @muhammademirsyah8037 11 місяців тому

    Love all of your content, keep it up!

  • @sadique_x_
    @sadique_x_ 11 місяців тому

    funny how I'll come across a video made today on something I'll learning today

  • @brNoMundo123
    @brNoMundo123 11 місяців тому

    Conteúdo incrível 👏👏👏👏

  • @johndevnoza4223
    @johndevnoza4223 11 місяців тому

    Love your videos. And i would love to see your teachings for next js

    • @cosdensolutions
      @cosdensolutions  11 місяців тому +2

      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 11 місяців тому

      @@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  11 місяців тому +1

      Learn React first definitely! Then if you want go to nextjs, but you definitely need the React foundation

    • @johndevnoza4223
      @johndevnoza4223 11 місяців тому

      @@cosdensolutions Thanks for the response

  • @JahangirKhan-t2p
    @JahangirKhan-t2p 2 місяці тому

    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.

  • @endlessnameless3613
    @endlessnameless3613 11 місяців тому

    Just what I need right now

  • @MadDogg3669
    @MadDogg3669 11 місяців тому +1

    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!

  • @AdemBenAbdallah-t6h
    @AdemBenAbdallah-t6h 11 місяців тому

    Best Channel that talk about react keep going

  • @VINOTHKUMAR-ey1yg
    @VINOTHKUMAR-ey1yg 10 місяців тому +1

    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..

  • @UkrScript
    @UkrScript 11 місяців тому

    Thank you, was very helpful

  • @nicolas_vl
    @nicolas_vl 10 місяців тому

    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

  • @romaghorjomeladze439
    @romaghorjomeladze439 11 місяців тому +1

    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

  • @ProdByGR
    @ProdByGR 8 місяців тому

    This the best approach

  • @Pareshbpatel
    @Pareshbpatel 7 місяців тому

    React: Protected Route Component, so clearly explained. Thanks, Darius
    {2024-05-30}

  • @TanNguyen-lj4zp
    @TanNguyen-lj4zp 7 місяців тому

    Can you show me what extensions you are using?

  • @aakashsingh3711
    @aakashsingh3711 9 місяців тому

    Can you please make a whole playlist of tutorial on react router dom? You make things very easy.

  • @ardianhotii
    @ardianhotii 11 місяців тому +1

    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 5 місяців тому

      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 5 місяців тому

      @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 5 місяців тому

      ​ @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 5 місяців тому +1

      @@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 5 місяців тому

      @@ardianhotii Good luck!

  • @foveromw
    @foveromw 9 місяців тому

    Quick and simple ❤

  • @gabru4477
    @gabru4477 11 місяців тому +2

    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 11 місяців тому

      I also want to know that

    • @cosdensolutions
      @cosdensolutions  11 місяців тому

      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 11 місяців тому

      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 11 місяців тому

      @@juanantoniovivaldy i am getting roles from my login api but i think that is not a good approach i need something different

    • @gabru4477
      @gabru4477 11 місяців тому

      @@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

  • @royerrrrutti9903
    @royerrrrutti9903 5 місяців тому

    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...

  • @gabrr.community
    @gabrr.community 11 місяців тому

    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.

  • @paleo3142
    @paleo3142 5 місяців тому

    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.

  • @RitikRaj-we2sc
    @RitikRaj-we2sc 10 місяців тому

    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.

  • @osamakaram3942
    @osamakaram3942 8 місяців тому

    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.

  • @capt_vj
    @capt_vj 10 місяців тому

    is this a higher order component? the ProtectedRoute?

  • @usamaansari4231
    @usamaansari4231 8 місяців тому

    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?

  • @HariharanArjunan-i1k
    @HariharanArjunan-i1k 10 місяців тому

    please teach about how to add common header file in createBrowerRouter technique

  • @heech6941
    @heech6941 4 місяці тому

    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

  • @sidpd
    @sidpd 7 днів тому

    how to manage that issignedin value?

  • @fahiyejr1930
    @fahiyejr1930 8 місяців тому

    How do I make my login page seperate, please help??

  • @Jacek2048
    @Jacek2048 3 місяці тому

    Great! Now I don't need any auth in my backend, I can just use React.

  • @youssefkhaled2113
    @youssefkhaled2113 11 місяців тому

    can i do the same using a layout and add my routes under this layout that does the same protection logic ?

  • @abjzzz
    @abjzzz 11 місяців тому +2

    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 5 місяців тому

      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.

  • @kalyaniingle8718
    @kalyaniingle8718 8 місяців тому

    Awesome content💚💚

  • @saadniaxi1623
    @saadniaxi1623 11 місяців тому

    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 😅

  • @bizmich_
    @bizmich_ 9 місяців тому

    how to protect /sign-in after when i signed-in?

  • @lucasirondesouzacamargo1540
    @lucasirondesouzacamargo1540 11 місяців тому

    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  11 місяців тому

      fair point, would work!

    • @belkocik
      @belkocik 11 місяців тому

      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​

  • @dsilver1330
    @dsilver1330 11 місяців тому

    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  11 місяців тому

      both are fine! Mern might be more versatile though

  • @FramerGaming
    @FramerGaming 11 місяців тому

    how to get that user i mean can you tell us the best practices for handling auth in react?

    • @juanantoniovivaldy
      @juanantoniovivaldy 11 місяців тому

      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  11 місяців тому

      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)

  • @jinshin.19
    @jinshin.19 9 місяців тому

    Hi to use this I have to do this right?
    {
    path: "/",
    element: (



    ),
    },
    {
    path: "/read/:id",
    element: (



    ),
    },
    {
    path: "/update/:id",
    element: (



    ),
    },

  • @iury664
    @iury664 11 місяців тому

    this way of import, import * as React from react isn't make the app be more weight?

    • @MohamedElguarir
      @MohamedElguarir 11 місяців тому +1

      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 11 місяців тому +1

      @@MohamedElguarir thanks

  • @ThanHtutZaw3
    @ThanHtutZaw3 11 місяців тому

    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 ?

  • @abdhelal
    @abdhelal 11 місяців тому

    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  11 місяців тому

      show a loading spinner until you get a user

  • @mfion1
    @mfion1 11 місяців тому

    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!

  • @Ganievs09
    @Ganievs09 11 місяців тому

    What if we want several routes to be protected? Should we Wrap all Components in ProtectedRoute Component or there is better way?

    • @cosdensolutions
      @cosdensolutions  11 місяців тому +1

      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 11 місяців тому

      Yeah I got what you mean. That's good approach. Thanks for your cutting edge videos.@@cosdensolutions

  • @lucasmachado6447
    @lucasmachado6447 11 місяців тому

    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  11 місяців тому

      nope, might actually be better because you can do it without an extra render

  • @abhinasregmi9742
    @abhinasregmi9742 11 місяців тому

    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  11 місяців тому +1

      You can, but this was an example. Your isSignedIn should come from the backend

    • @abhinasregmi9742
      @abhinasregmi9742 11 місяців тому

      @@cosdensolutions ok thanks for the help

  • @ericng3673
    @ericng3673 9 місяців тому

    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  9 місяців тому +1

      You let the user state redirect. When user state changes, redirect. No race condition 😁

  • @tamaniphiri
    @tamaniphiri 11 місяців тому

    Solutions for modern day problems, great stuff🚀💯

  • @UFO_808
    @UFO_808 11 місяців тому

    Bro where are you from, if it's not a secret? 😀

    • @cosdensolutions
      @cosdensolutions  11 місяців тому +1

      Originally from Romania

    • @UFO_808
      @UFO_808 11 місяців тому

      @@cosdensolutions Lol I'm from Serbia bro, I wisited Timișoara last winter 😄

    • @cosdensolutions
      @cosdensolutions  11 місяців тому

      I live in serbia atm hahaha, serbian gf

    • @UFO_808
      @UFO_808 11 місяців тому

      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? 😄

  • @chukwukaeze4736
    @chukwukaeze4736 6 місяців тому

    Why is bro recording in dark theme

  • @AkshayParkad
    @AkshayParkad 11 місяців тому

    wrap {children } in div or react fragment at the time of return {children}..otherwise it may cause a problem in some cases

  • @juliaof.kataleko7595
    @juliaof.kataleko7595 7 місяців тому

    Best teacher ever!!

  • @davidhusted817
    @davidhusted817 11 місяців тому

    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 😊

  • @jeandedieuiradukunda6079
    @jeandedieuiradukunda6079 6 місяців тому

    you're amazing

  • @qureshiowais6951
    @qureshiowais6951 10 місяців тому

    why not keep it !user because it seem better as if any false will get back to sign in page!!!

  • @VvazoLsky
    @VvazoLsky 10 місяців тому

    omagad , this is tutorial wish me search

  • @tanmay4l
    @tanmay4l 11 місяців тому

    Custom hooks

  • @ignacioarriagadairiarte4338
    @ignacioarriagadairiarte4338 11 місяців тому

    nice video

  • @deepaksurya9742
    @deepaksurya9742 11 місяців тому

    Start NextJs

  • @amitrana3053
    @amitrana3053 11 місяців тому

    Osm learning

  • @phamtienthinh1795
    @phamtienthinh1795 10 місяців тому

    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

  • @lokeshkaushik1812
    @lokeshkaushik1812 11 місяців тому

    First