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
You, sir, have a soothing voice.
@mayurmewada8959
2 жыл бұрын
Which theme he is using...?
Amazing 4yr old video that's still relevant today. Thank you for making this.
omg i've been looking this for 2 hours, thank you a lot :DDD
@slmshady539
3 жыл бұрын
I spent entire 2 days looking for this.
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.
Thanks, Bruh. You did justice to this topic. Cleared all doubts
Just like what I need
10/10 honestly, great video and explanation!
Really efficient tutorial man! thanks for your help, cheers from Brazil ;)
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
4 жыл бұрын
Today, you sir were my hero. Thank you.
@suketupatel174
4 жыл бұрын
@@bryanamezcua4680 glad to be of help
@chill-_-839
3 жыл бұрын
or import Fragmant and use
the best tutorial on React Router I saw... nice broth
I really like this tutorial. It's perfect ! Thank you very much ! :)
Mention of "withRouter" saved my live🙏🏻🙏🏻🙏🏻🙏🏻
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!!
Thanks for sharing this project! good luck for you.
You solved my problem. Thanks so much!
Sir, You pick an easy way to teach , I like this, Few can do this. It is very hard to teach simple.
Thanks men, thats what i have been searching for :)
Now, I really didn't expect this to end up being a perfect ASMR video
Excellent info.. It's a gem.👍 Thanks a ton 🙏
Thank u from Colombia. It was very helpful for me
Simple and elegant. Nice.
Straight to the point. Thanks!
smooth voice and clear explanation.thanks
This is exactly what I needed
Thank you so much for amazing explanation!
It really helped a lot, thank you!
Quality content right there! Thanks!
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
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.
superb sir, you explained it very well
Really awesome video Very simple and subjective
Really good, thanks!
This is awesome. Thank you very much ❤️
Awesome job, keep the good work ...
You are very good teacher
@nickkarnik9688
5 жыл бұрын
Thank you so much! I really appreciate the kind words.
Thanks you very much for the video. i got stuck with this issue and you helped me solve it
Very clear explanation, thanks
Just awesome!!! Thanks a lot.
Great tutorial, easy to follow. Btw, what font do you use?
Thank you for this video. I want to ask a question. Is it higher order component?
This is been very helpful, cleared few questions I had. Thank you.
Thank you man. You saved me ❤️
Best tutorial I saw for react router can u make video on design patterns in react
I am grateful
The Video was really helpful........Thanks a million..
Hi ! Great video! thanks a million! Do you have videos on databases? So the password etc is not stored in the browser i mean
Thanks it really helped me
Great...it worked. really helpful. thanks
Thanks, good explanation.
thanks dude!
thanks this was really help full .thanks alot
Good one. simple and superb .
Hi, what if we want to protect our whole application with the protected router what should we do then
Thank you!
nice tutorial, thanks
amazing thanks
Very useful .. THanks
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.
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?
You are a genius
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
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.
Good Tutor sir. Thank....
it's amazing tuturial
man you are awesome!
what editor is this, and is the shema theme you use on it plz?
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 \> ) ```
Thanks bro!
Muito bom, conteúdo excelente!
The last thing that I would like to see is try to get access to /app when you logged out
@rianiregho1831
3 жыл бұрын
yup, I m too :(
@createlifejr
3 жыл бұрын
Me too. I was literally waiting for that! 😅
Thanks!
thank you very much sir
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'
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.
what about if i want to write it like this with the new API : instead of how should component be?
Can you please tell me which code editor you are using ?
great vid
Thank you
thanks, simple solution ✅
Bro Good tut ;) ! this step of passing a component @ 08:55 was somehow confusing , can you please amplify this step :)
@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". :)
thank you so much
you're a fucking god for this. thank you.
What if l want login component to not be accessible after logging in?
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
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
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
5 жыл бұрын
The Net Ninja has a great series on Passport.JS and OAuth if that's any help. kzread.info/dash/bejne/pZWfs8Segs3Np8o.html
thank you
Thanks u!
what is the IDE used in the video? and which is the recommended community IDE's available
Thanks, sir its very usefull
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
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
5 жыл бұрын
I would love it! I am looking forward! :)
@rubinskyzlatrovich6731
5 жыл бұрын
Nick Karnik please yes
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
3 жыл бұрын
this is just example, in real project this will be handle by backend.
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?
But all the routes are on the bundle, they are not really “private” right? can this be solved without ssr?
@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
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
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
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.
Thanks
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..
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
5 жыл бұрын
Yes, because a basic react tutorial for beginners is going to show you how to make an enterprise ready application... 🙄
how to use partial components in other component. but not in login component remianing SPA
thanks
If you are using jwt, can you control access that way (like if they have admin privileges?)
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.
Can Any one help me ? i am getting the below error ----- > ./src/protected.route.js TypeError: Cannot read property 'forEach' of undefined
@dragonminja246
4 жыл бұрын
I have the same issue when copying it over to react
🙏🏻🙏🏻🙏🏻 thanks and thanks and thanks🙏🏻🙏🏻🙏🏻
Thanks man....