DEV Community

Cover image for Protect Your Routes in React
Mohamed Amine Fh
Mohamed Amine Fh

Posted on • Edited on

Protect Your Routes in React

If you're using react router in your App, then you probably wanted to protect some routes from specific users, or to Redirect some users to their own page or component.

so what to do ?

In this blog we'll see How to handle that with some simple checks

checks

So at the beginning this is how our App looks like

protectedRoute2

At this point every user can access those two components (Admin, Home)

But that's not what i want, I want just the admin to have access to the "/admin" route.

And those who don't have access to that route, I need to redirect them to the Home Page ("/" route)

So the 1st Step is to create the ProtectedRoute Component.

You can create it in the same file, but for a cleaner code we'll create it on a new file

1- Create a file and name it to what you want. I'll name it protectedRoute.js.

2- Paste this code in that file

protectedRoute1

So basically we check if there is a token stored in our LocalStorage or not.

If The check is Truthy then he Have access to that route.
If Not, He will be Redirected to the Home Page (thanks to the <Redirect /> Component).

You need to change that check to suit your case.

Don't forget to export your Component.

3- Finally we'll use that ProtectedRoute in our App

Import The ProtectedRoute Component from where you created it
you can name it what you want if you export it with the default

protectedRoute3

So here we need to change The

<Route exact path="/admin" component={Admin} />

with

<ProtectedRoute exact path="/admin" component={Admin} />

And that's it 🎉, Go Try it out.

Top comments (0)