DEV Community

Cover image for How to Create Public And Private Routes using React Router
Nilanth
Nilanth

Posted on • Updated on • Originally published at javascript.plainenglish.io

How to Create Public And Private Routes using React Router

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

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, SignUp, Forgot Password, Reset Password. In simple words, These routes can be accessed before login into 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 can see. 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.

Get more updates on Twitter.

You can support me by buying me a coffee ☕

eBook

Debugging ReactJS Issues with ChatGPT: 50 Essential Tips and Examples

ReactJS Optimization Techniques and Development Resources

More Blogs

  1. Redux Toolkit - The Standard Way to Write Redux
  2. 5 Packages to Optimize and Speed Up Your React App During Development
  3. How To Use Axios in an Optimized and Scalable Way With React
  4. 15 Custom Hooks to Make your React Component Lightweight
  5. 10 Ways to Host Your React App For Free
  6. How to Secure JWT in a Single-Page Application
  7. React 18 Alpha: A Quick Overview
  8. Redux Auth Starter: A Zero Config CRA Template

Top comments (8)

Collapse
 
bob_sarfo profile image
Bob SS

Thanks for sharing ...love this

Collapse
 
baloukaulrich6 profile image
baloukaulrich6

I encountered a problem with react v6 to create protected routes I don't know where it is blocking

```import React from 'react';
import { Outlet, Navigate } from 'react-router-dom';

const PrivateRoute = ({component, token, children}) => {
if(!token){
return ;
} else {
return
}

}

export default PrivateRoute;



Enter fullscreen mode Exit fullscreen mode
Collapse
 
jahidhasan profile image
Jahid Hasan

Thanks for sharing ❤️
but i noticed a problem. when user logged in and redirect to private route it work well but when the page refresh its return to login page.

Collapse
 
randomhead2 profile image
Moskva.

Lovely article, thanks for sharing.
I noticed something however. Because the path of PrivateRoute is set to '/' with no exact, It seems the 404 path is never matched

Collapse
 
maistutony profile image
maistutony

Great article I found it usefull

Collapse
 
imsiaw profile image
Imsiaw

very useful

Collapse
 
sagarpakhrin profile image
Sagar Lama

You could also determine isAuthenticated in side the Protected route instead of having to pass it as a prop in every route

Collapse
 
codingee profile image
Samuel Archibong

Thanks for sharing, please if there's more don't hesitate to share.