Working with protected routes in ReactJS

Deinyefa
1 min readJun 21, 2019
Photo by Denys Nevozhai on Unsplash

While building web applications, we may find that some routes need to be hidden from anonymous users. I have found this need arise more often recently, and find that using a Higher Order Component for those routes work pretty well for my use-cases.

<PrivateRoute path="/dashboard" component={Dashboard} />

Example

Below is an example of how the <PrivateRoute /> HOC could look.

firebase was used for authentication here

In a nutshell, <PrivateRoute /> takes another Component and passes it to <Route />. If the user is not anonymous, the desired, private component is rendered by <Route />. If not, the user is redirected to the login page.

<PrivateRoute /> can then be placed right alongside other public <Route /> components inside <BrowserRouter />

Final Thoughts

I wonder if there’s a way to group all public and private routes separately in order to only have to check if the user is not anonymous once, at a “private routes” entry point…

--

--

Deinyefa

UX Engineer ⋅ JavaScript ⋅ Hooked on ReactJS