Protected Routes in React using React Router

In this video, we will create a protected route using React Router. This route is accessible only when the user is logged in.
Link to CodeSandbox: codesandbox.io/s/ol6z72kjy9
Tutorial from Nick Karnik. Check out his KZread channel: / @nickkarnik9688
Nick on Twitter: / theoutlander
--
Learn to code for free and get a developer job: www.freecodecamp.org
Read hundreds of articles on programming: medium.freecodecamp.org

Пікірлер: 214

  • @rogerodipo3499
    @rogerodipo34994 жыл бұрын

    You, sir, have a soothing voice.

  • @mayurmewada8959

    @mayurmewada8959

    2 жыл бұрын

    Which theme he is using...?

  • @adeleke5140
    @adeleke5140 Жыл бұрын

    Amazing 4yr old video that's still relevant today. Thank you for making this.

  • @stevendiaz7374
    @stevendiaz73745 жыл бұрын

    omg i've been looking this for 2 hours, thank you a lot :DDD

  • @slmshady539

    @slmshady539

    3 жыл бұрын

    I spent entire 2 days looking for this.

  • @olendaelhousen1552
    @olendaelhousen15525 жыл бұрын

    Thanks - this was really helpful. I like that you kept everything simple and didn't get overly complicated, that made it very easy to pick up the concept and start coding.

  • @simonkalu
    @simonkalu4 жыл бұрын

    Thanks, Bruh. You did justice to this topic. Cleared all doubts

  • @chrisdanevalla3293
    @chrisdanevalla32935 жыл бұрын

    Just like what I need

  • @morapedimasima9753
    @morapedimasima97533 жыл бұрын

    10/10 honestly, great video and explanation!

  • @erichcasagrandeperusso5493
    @erichcasagrandeperusso54933 жыл бұрын

    Really efficient tutorial man! thanks for your help, cheers from Brazil ;)

  • @suketupatel174
    @suketupatel1744 жыл бұрын

    if anyone is using routes with children: e.g. then do this: import React from "react" import {Route} from "react-router-dom" const ProtectedRoute = ({children,...rest}) =>{ return ( {children} ) } export default ProtectedRoute;

  • @bryanamezcua4680

    @bryanamezcua4680

    4 жыл бұрын

    Today, you sir were my hero. Thank you.

  • @suketupatel174

    @suketupatel174

    4 жыл бұрын

    @@bryanamezcua4680 glad to be of help

  • @chill-_-839

    @chill-_-839

    3 жыл бұрын

    or import Fragmant and use

  • @ricardinhofreestile
    @ricardinhofreestile4 жыл бұрын

    the best tutorial on React Router I saw... nice broth

  • @Jwaana
    @Jwaana4 жыл бұрын

    I really like this tutorial. It's perfect ! Thank you very much ! :)

  • @vishwasr8446
    @vishwasr84463 жыл бұрын

    Mention of "withRouter" saved my live🙏🏻🙏🏻🙏🏻🙏🏻

  • @bidhyapokharel4687
    @bidhyapokharel46873 жыл бұрын

    Thank you so much for such a beautiful Video....Had not slept since last night since I was trying to do it by reading Documentations...You're so great....Wish I had explored this thing before!!

  • @otwoc
    @otwoc5 жыл бұрын

    Thanks for sharing this project! good luck for you.

  • @TS-qf2km
    @TS-qf2km4 жыл бұрын

    You solved my problem. Thanks so much!

  • @ankitavay1947
    @ankitavay19474 жыл бұрын

    Sir, You pick an easy way to teach , I like this, Few can do this. It is very hard to teach simple.

  • @Max-kg9sl
    @Max-kg9sl4 жыл бұрын

    Thanks men, thats what i have been searching for :)

  • @Elliewebd
    @Elliewebd2 жыл бұрын

    Now, I really didn't expect this to end up being a perfect ASMR video

  • @RN-ru2rj
    @RN-ru2rj5 жыл бұрын

    Excellent info.. It's a gem.👍 Thanks a ton 🙏

  • @MrEdward2553
    @MrEdward25534 жыл бұрын

    Thank u from Colombia. It was very helpful for me

  • @kyoungd
    @kyoungd5 жыл бұрын

    Simple and elegant. Nice.

  • @JoshAmore31
    @JoshAmore313 жыл бұрын

    Straight to the point. Thanks!

  • @recepozturk6711
    @recepozturk67114 жыл бұрын

    smooth voice and clear explanation.thanks

  • @hileamlakmulugeta5959
    @hileamlakmulugeta59593 жыл бұрын

    This is exactly what I needed

  • @ytwatcher181
    @ytwatcher1813 жыл бұрын

    Thank you so much for amazing explanation!

  • @JsWithRaj
    @JsWithRaj3 жыл бұрын

    It really helped a lot, thank you!

  • @shibah9345
    @shibah93452 жыл бұрын

    Quality content right there! Thanks!

  • @syednoohu8692
    @syednoohu86924 жыл бұрын

    New to ProtectedRoute...sorry if my question is naive. Q : Arguments in the ProtectedRoute we destructing {component : Component, ...rest}, my doubt is why not the assignment is other way around, i.e. {Component : component, ...rest}, since we are passing the props as 'component' only, not 'Componenet' Thanks

  • @ammarfy

    @ammarfy

    3 жыл бұрын

    const { component } = props ; // how you normally do to destructure an object const { component: Component } = props; // Destructure an object then give it a new variable name, Component In React every component name should always start with Uppercase because of JSX rules. Hence, assigning 'component' to Component is needed.

  • @vickyvirat5166
    @vickyvirat51664 жыл бұрын

    superb sir, you explained it very well

  • @nagarajukp7820
    @nagarajukp78203 жыл бұрын

    Really awesome video Very simple and subjective

  • @gaos94
    @gaos945 жыл бұрын

    Really good, thanks!

  • @jpcalvo6699
    @jpcalvo66993 жыл бұрын

    This is awesome. Thank you very much ❤️

  • @faradniftaly8893
    @faradniftaly88934 жыл бұрын

    Awesome job, keep the good work ...

  • @Softwareengineeringdev
    @Softwareengineeringdev5 жыл бұрын

    You are very good teacher

  • @nickkarnik9688

    @nickkarnik9688

    5 жыл бұрын

    Thank you so much! I really appreciate the kind words.

  • @rajasaid8227
    @rajasaid82273 жыл бұрын

    Thanks you very much for the video. i got stuck with this issue and you helped me solve it

  • @robindalehayden
    @robindalehayden3 жыл бұрын

    Very clear explanation, thanks

  • @md.mainuddin8211
    @md.mainuddin82114 жыл бұрын

    Just awesome!!! Thanks a lot.

  • @yanurmal
    @yanurmal3 жыл бұрын

    Great tutorial, easy to follow. Btw, what font do you use?

  • @mertcancetinkaya7648
    @mertcancetinkaya76483 жыл бұрын

    Thank you for this video. I want to ask a question. Is it higher order component?

  • @oasane
    @oasane3 жыл бұрын

    This is been very helpful, cleared few questions I had. Thank you.

  • @pasindupansilu6046
    @pasindupansilu60463 жыл бұрын

    Thank you man. You saved me ❤️

  • @ashishchiluka8912
    @ashishchiluka89124 жыл бұрын

    Best tutorial I saw for react router can u make video on design patterns in react

  • @christianalejandroherrejon6819
    @christianalejandroherrejon68194 жыл бұрын

    I am grateful

  • @rafihasan4061
    @rafihasan40613 жыл бұрын

    The Video was really helpful........Thanks a million..

  • @tekqist28
    @tekqist284 жыл бұрын

    Hi ! Great video! thanks a million! Do you have videos on databases? So the password etc is not stored in the browser i mean

  • @kumargagare6154
    @kumargagare61544 жыл бұрын

    Thanks it really helped me

  • @bharathynasar3338
    @bharathynasar33382 жыл бұрын

    Great...it worked. really helpful. thanks

  • @prathameshchavan3953
    @prathameshchavan39532 жыл бұрын

    Thanks, good explanation.

  • @zoeygrimes07
    @zoeygrimes074 жыл бұрын

    thanks dude!

  • @tube-rp1nb
    @tube-rp1nb2 жыл бұрын

    thanks this was really help full .thanks alot

  • @Dipenparmar12
    @Dipenparmar123 жыл бұрын

    Good one. simple and superb .

  • @zillboy
    @zillboy4 жыл бұрын

    Hi, what if we want to protect our whole application with the protected router what should we do then

  • @sergeymigel4680
    @sergeymigel46804 жыл бұрын

    Thank you!

  • @ahmadyahya1919
    @ahmadyahya19193 жыл бұрын

    nice tutorial, thanks

  • @shahab09362835101
    @shahab093628351015 жыл бұрын

    amazing thanks

  • @zakiarahmoune7458
    @zakiarahmoune74582 жыл бұрын

    Very useful .. THanks

  • @AnteZivkovic
    @AnteZivkovic3 жыл бұрын

    What if the routes I want to protect use the render prop because they render components that have props themselves? I get errors using this method.

  • @prezesgustaf7268
    @prezesgustaf72684 жыл бұрын

    So where should we read the data? Store user object in LocalStorage and then read data from it? Its good practise? so what if someone manualy change localStorage and change e.g role from user to admin?

  • @heunsigjo7484
    @heunsigjo74844 жыл бұрын

    You are a genius

  • @maheshtak5120
    @maheshtak51205 жыл бұрын

    I would like to know, what happenes if without clicked on login i tried to visit app page through url... Will it visit to app page or it will give 401 error as wrote in Protecting Route ?

  • @TheAqui2000

    @TheAqui2000

    4 жыл бұрын

    I know it's a year later, but for anyone wondering now it would just redirect you back to whatever page you set it to in your private route . So if you go a protected route url without logging in, in your private route component use the Redirect component to take the user back to the main page if not logged in.

  • @drlucky5474
    @drlucky54744 жыл бұрын

    Good Tutor sir. Thank....

  • @muhriddinxusniddinov9015
    @muhriddinxusniddinov90152 жыл бұрын

    it's amazing tuturial

  • @TheShubham67
    @TheShubham673 жыл бұрын

    man you are awesome!

  • @abanoubashraf1308
    @abanoubashraf13083 жыл бұрын

    what editor is this, and is the shema theme you use on it plz?

  • @SyedShujashah
    @SyedShujashah Жыл бұрын

    3:00 Thank you for these awesome videos, Here's a tip for best practices for new JS or react enthusiasts. When you're just returning some JSX from a component, you can go ahed and remove curly braces and 'return' syntax such as: ``` const Hello = () => ( Hi \> ) ```

  • @zahidshaikh3122
    @zahidshaikh31222 жыл бұрын

    Thanks bro!

  • @PauloHenrique-qh3li
    @PauloHenrique-qh3li3 жыл бұрын

    Muito bom, conteúdo excelente!

  • @Ixtinkt
    @Ixtinkt3 жыл бұрын

    The last thing that I would like to see is try to get access to /app when you logged out

  • @rianiregho1831

    @rianiregho1831

    3 жыл бұрын

    yup, I m too :(

  • @createlifejr

    @createlifejr

    3 жыл бұрын

    Me too. I was literally waiting for that! 😅

  • @DennisTurbay
    @DennisTurbay3 жыл бұрын

    Thanks!

  • @theethicalh3707
    @theethicalh37073 жыл бұрын

    thank you very much sir

  • @sneharajput4151
    @sneharajput41514 жыл бұрын

    Hello Sir, I am facing some issue in my project, i have used BrowserRouter for Route but after create build then run on browser and after refresh page 'object not found error showing' but i have used HashRouter for Route then after create build run on browser, project run perfect. Please help me to solve this error 'object not found after page refresh'

  • @mattmarkus4868
    @mattmarkus48683 жыл бұрын

    In your protected route (the layout), won't you have to load different components depending on what they do in the layout page? Like say your layout has a navbar with different links to different components within the main area of your layout/nav page. Will these components still be protected, or would you have to make every component you want to protect a protected route in your App.js ? Thanks, great tutorial.

  • @cosmin4437
    @cosmin44374 жыл бұрын

    what about if i want to write it like this with the new API : instead of how should component be?

  • @amirsohel9260
    @amirsohel92604 жыл бұрын

    Can you please tell me which code editor you are using ?

  • @shanindrakumar9944
    @shanindrakumar99444 жыл бұрын

    great vid

  • @vishwasr8446
    @vishwasr84463 жыл бұрын

    Thank you

  • @PeterPalmerSoftware
    @PeterPalmerSoftware3 жыл бұрын

    thanks, simple solution ✅

  • @TheAlyZidan
    @TheAlyZidan5 жыл бұрын

    Bro Good tut ;) ! this step of passing a component @ 08:55 was somehow confusing , can you please amplify this step :)

  • @alextkd2003

    @alextkd2003

    5 жыл бұрын

    it is destructuring, you can use ****** in App.js function; and ***const SecretRoute = ( { Component, ...rest } )*** in protected.route.js. A component have to be named capitalize, so he use the syntax { component: Component } because the father component have the prop name "component". :)

  • @hafsaelkoumikhi9200
    @hafsaelkoumikhi92002 жыл бұрын

    thank you so much

  • @lilpece1950
    @lilpece19505 жыл бұрын

    you're a fucking god for this. thank you.

  • @astritspanca2723
    @astritspanca27235 жыл бұрын

    What if l want login component to not be accessible after logging in?

  • @256k_
    @256k_5 жыл бұрын

    Auth is something that's been really confusing to me to be honest, im very familiar with react and JS and everything in this video but i would relaly appreciate if there could be more in depth videos like this (which was great) about auth itself, different ways of handling auth in an application and whether write your own auth like you did or maybe use a package to handle it?

  • @nickkarnik9688

    @nickkarnik9688

    5 жыл бұрын

    Thanks, @fayekhelmi! I wanted to break the videos down to focus on specific areas. Originally, I planned on creating the server side using PassportJS and wiring everything, but that meant getting into a bunch of other things at the same time. I might do a combined video showing everything end-to-end in the future . The next video might just focus on integrating PassportJS.

  • @millexuan

    @millexuan

    5 жыл бұрын

    @@nickkarnik9688 any quick hints on how to handle the passport redirect callback from the Express server in the React auth file? Great video!

  • @yousof77

    @yousof77

    5 жыл бұрын

    The Net Ninja has a great series on Passport.JS and OAuth if that's any help. kzread.info/dash/bejne/pZWfs8Segs3Np8o.html

  • @mohamedalhoony
    @mohamedalhoony4 жыл бұрын

    thank you

  • @franz-universe
    @franz-universe5 жыл бұрын

    Thanks u!

  • @ykk522
    @ykk5223 жыл бұрын

    what is the IDE used in the video? and which is the recommended community IDE's available

  • @piriyadarrshans988
    @piriyadarrshans9883 жыл бұрын

    Thanks, sir its very usefull

  • @tomtobac
    @tomtobac5 жыл бұрын

    I would like to know how to handle authentication async like begin redirect by Auth service with URL with params then asking to the server for extra data (like accounts associated) and then redirect the user to app itself. Also would be awesome to store this auth data in the localStorage :) Thanks! Great video!

  • @nickkarnik9688

    @nickkarnik9688

    5 жыл бұрын

    Thanks, @SomethingOfHappy! Originally, I planned on doing that, but the scope of the video gets very large. I wanted to focus on specific areas to get the point across. I will consider doing a combined video after all the smaller ones are done. Perhaps, I could consider turning this into a series where I incrementally start building this stuff. Thoughts?

  • @tomtobac

    @tomtobac

    5 жыл бұрын

    I would love it! I am looking forward! :)

  • @rubinskyzlatrovich6731

    @rubinskyzlatrovich6731

    5 жыл бұрын

    Nick Karnik please yes

  • @nassar_productions
    @nassar_productions3 жыл бұрын

    importing auth in different js files is creating instances of them. How are you managing to set login= true in one page, then importing auth in another page and the value is still true??

  • @nguyenhanh9479

    @nguyenhanh9479

    3 жыл бұрын

    this is just example, in real project this will be handle by backend.

  • @gauravoberoi962
    @gauravoberoi9624 жыл бұрын

    what about if i am signed in, and i click on browser back button? will it shoow me the signed in page? if yes, then then it seems wrong. if no, then how to do it?

  • @rubinskyzlatrovich6731
    @rubinskyzlatrovich67315 жыл бұрын

    But all the routes are on the bundle, they are not really “private” right? can this be solved without ssr?

  • @nickkarnik9688

    @nickkarnik9688

    5 жыл бұрын

    You are correct about that. Normally, you will have client-side routes for a Single Page Application (SPA) and server-side routes (via API's) for SPA and Server Side Rendering (SSR). You need to ensure that the user has permissions to access both. Even if the user managed to load a route on the client, the server should have another layer of verification where it won't return data if you're not authorized. In addition, your Data Access Layer and Database should have yet another level of verification as a safeguard. Does that answer your question?

  • @daniyalasif983

    @daniyalasif983

    5 жыл бұрын

    If I understand your question, you mean to say that these Protected Routes are only client side and not server side. You can easily create server side authentication with with middlewares (In Express) I have done this for my application before, I had client side protection and I also had a middleware which would check if the user is an admin or sign in and so on which would then send an error or give access depending on how the middleware evaluates.

  • @rubinskyzlatrovich6731

    @rubinskyzlatrovich6731

    5 жыл бұрын

    All the things I read are that the person can enter the route and then you validate on the server the info that comes but the user is already on the page. Is there a way to ask the server first and let the server render the page? Like a mix of ssr and spa? Like together or something?

  • @nickkarnik9688

    @nickkarnik9688

    5 жыл бұрын

    Normally, you would implement an app as either SSR or SPA. It is not uncommon to mix them. You would load SSR content either as a page of its own outside of the React app or inside the React app. In the first scenario, a simple link referencing a server URL should do it (I haven't tried it), and in the other case, you request that static page via AJAX and load it in a div.

  • @vishwasr8446
    @vishwasr84463 жыл бұрын

    Thanks

  • @kvieres
    @kvieres4 жыл бұрын

    is it the right way to do this?, there isn't a plugin or something that avoid put this interventions in each part of my code..

  • @webmintutorials8939
    @webmintutorials89395 жыл бұрын

    One thing I noticed is that every lesson on React about Protected Routes and user authentication are copied straight up from the reacttraining.com. This example doesn't solve any problem on a major application where security and performance it's on account. In a real world scenario, you'll have a server-side authentication flow such as PassportJS with an endpoint (API) where you can make a AJAX request to check if user is authenticated and have access to certain routes.

  • @keviin608

    @keviin608

    5 жыл бұрын

    Yes, because a basic react tutorial for beginners is going to show you how to make an enterprise ready application... 🙄

  • @bilawalali6810
    @bilawalali68104 жыл бұрын

    how to use partial components in other component. but not in login component remianing SPA

  • @metromota
    @metromota4 жыл бұрын

    thanks

  • @ErickG
    @ErickG3 жыл бұрын

    If you are using jwt, can you control access that way (like if they have admin privileges?)

  • @davis4010
    @davis40103 жыл бұрын

    I suppose in real life situation that auth.isAuthenticated call should be made on every protected view attempt? Or just save it in state? I tried to do axios get and confirm the jwt token is valid, yet it seems somehow that check fails - undefined is returned when protectedrout component waits for that reply. Hmm, a little bit lost there.

  • @arunkaiser
    @arunkaiser4 жыл бұрын

    Can Any one help me ? i am getting the below error ----- > ./src/protected.route.js TypeError: Cannot read property 'forEach' of undefined

  • @dragonminja246

    @dragonminja246

    4 жыл бұрын

    I have the same issue when copying it over to react

  • @vishwasr8446
    @vishwasr84463 жыл бұрын

    🙏🏻🙏🏻🙏🏻 thanks and thanks and thanks🙏🏻🙏🏻🙏🏻

  • @josephsam2145
    @josephsam21452 жыл бұрын

    Thanks man....