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