Private routes with React-router-DOM

Tom Large
2 min readJun 16, 2018

If you have been developing in React then you have probably come across React-router-dom. One thing I was looking for when I started the using this was private routes.

I was creating a dashboard web app but needed this to be locked down if a user is not logged in. I also didn’t want Google to index the dashboard pages. Below I’m going to show you the code I use across my apps for private routes.

This something I use while i’m developing the front end of my web app and then I will out the logic later

Above is a the component you can use across your app. I have used localStorage while I’m developing the front-end this way I can add the logic later.

To then use the component I import this into where I’m setting up my routes.

Route is where anyone can access these

As you can see you can just use this as a route with the same props. It goes without saying that if you was to use this on a live app with localStorage users would just be able to add this in there inspector but this is where you would change this to your logic for your login or how you manage you auth system.

Let me know if you need anything else!

--

--