How to Create Public And Private Routes using React Router

Nilanth
JavaScript in Plain English
2 min readAug 9, 2021

--

Steps for writing public and private routes in React app using React Router

Photo by Bram Naus on Unsplash

When developing a React application with authentication, we might require public and private routes. Let’s first see what they are.

Public Routes

Public routes are log in, sign-up, forgot password, reset password. In simple words, these routes can be accessed before logging in to the app.

Private Routes

Private Routes vary based on the apps, For example, Dashboard, User Profile, App Settings, Home, etc. In simple words, these routes can be accessed only after login.

The constraints for public and private routes are that public routes should not be accessed after login and private routes should not be accessible before login.

In this article, we will see how this is done — how to create public and private routes using react-router for your React apps. Let’s start

Public Routes

First, let us create a PublicRoute.js component to handle public route conditions as below

As you can see in the above code, The Public route component receives 3 props like children, isAuthenticated and …rest . If the user is authenticated, He will be redirected to the Home screen and he can only access the public routes if he is not authenticated(Logged in).

Private Routes

The private route component is similar to the public route, the only change is that redirect URL and authenticate condition. If the user is not authenticated he will be redirected to the login page and the user can only access the authenticated routes If he is authenticated (Logged in).

Protected Routes

The protected Route component is used to map all the authenticated routes as below

Authenticated routes are defined as below in routes.js

Integrating Routes

Now let's integrate our route components to App.js as below

Here we have wrapped non-authenticated routes with <PublicRoute /> component and authenticated routes with <PrivateRoute /> component. We have used suspense to add lazy loading to components.

Now we have configured Private and Public Routes. If there is no match <NoFoundComponent /> will be rendered.

Conclusion

Public and Private routes will also restrict accessing the previously visited routes using the browser back button after logout. I hope you have found this useful. Thank you for reading.

More content at plainenglish.io

--

--