Home > ReactJS > How to Create Public and Private Routes with React Router?

How to Create Public and Private Routes with React Router?

If you are looking for a way to create public and private routes with the help of react-router in react application, then you are in right place.

We will use React Router library for routing. It is one of the top react library. It allows navigating from one component to another component by changing the URL in the browser.

The current version of React Router is v6 and it has many new features from the previous versions. You can easily implement it in your react application.

So, in this tutorial, we will use the React Router library to create public and private routes in react. We will explain it step by step, so you don’t get stuck when you implement your project.

Let’s get start with creating a react application having multiple components.

Create React Project

First thing you have to create a react project. If you already have installed the react application then you can skip this step.

To create the react application, use the following command in your terminal. It will download the default state of react application files and then you can start on it.

Install React Router

Now you have to install the react-router-dom package in your react application. It will manage all the routing navigation in the application.

Setup BrowserRouter

Ok now you have installed React Router’s dependency and we can use it. So first of all we will setup the <BrowserRouter> component.

<BrowserRouter> is the recommended interface for running React Router in a web browser. It will store the current location in the browser’s address bar and navigates using the browser’s history stack.

To implement <BrowserRouter> in react application, open the src/index.js file in your favirote text editor (VS Code, Sublime, Notepad++).

Now import the BrowserRouter from the react-router-dom package at the top of the component file. Then wrap your <App /> component in a <BrowserRouter>.

index.js

Now you can use React Router anywhere in your react application and make a routes navigation system to switch one component to another.

We will create now public and private routes using the React Router in our react application. Continue to read the following steps.

Private Route Component

The Private Route component is the main hub for all private routes in the application. Private Routes are those routes that can only be accessible to logged-in users. If users are logged out and try to access the private routes, they will redirect to the sign-in page.

Create the /Routes folder inside the /src folder and create a PrivateRoute.js file in it. In this file, we will define the logic which will protect our private routes. See the following code for reference.

PrivateRoute.js

Explanation: In the above code, we made a function component as a PrivateRoute and exported it. Then we have made the login condition to check whether a user is logged in or not.

In this code reference, we checked thourgh localStorage item key because we had set up the localStorage key when a user successfully login. You can make this login as you want, it’s up to you.

So logic will check if a user is not logged in then it will redirect to the /login page. We used the <Navigate /> component of react-router v6 for a redirect.

The <Navigate /> component is the replacement of <Redirect /> component of older version.

OK, after checking the condition, it returns the {children} component of the private route. You will better understand this when we will create the routes below.

Public Route Component

On the other hand, Public route components are accessible to all the users, even if they are logged in or not. These routes can also access logged-in users like about page, contact page, etc.

We will also restrict some pages to access in this Public component if the users are already logged in. The restricted page like login, signup, and forgot password page, these pages don’t make sense for logged-in users.

So create a component PublicRoute.js in /Routes folder. Here we will define the logic to restrict the restricted pages and continue with the public pages.

PublicRoute.js

Explanation: In the above code, we made a PublicRoute function component. Then we have made logic for restricted pages for logged-in users.

It will check the localStorage key that you will have to define on login success. So it will check if a user already logged in then it will redirect to the /dashboard page or any other page where you want to redirect.

And if users are not logged in then it will continue with their {children}, which means all the public pages.

Main Route Component

Now we have created PublicRoute and PrivateRoute components with the logic, now we will use them in this main component file.

In this main component, we will define all the routes for our application and wrap the routes components in <PublicRoute> and <PrivateRoute>.

Let’s create a file Main.js in the /Routes folder and add the basic structure of react component. Now import the PublicRoute and PrivateRoute components in this file.

Then create a function that defines all the routes with their path. Make sure you are using the new version v6 of react-router. See the following code for reference.

Main.js

Explanation: So in the above Main function component, we have imported <Routes> and <Route> from react-router-dom and also all the page components that we want to set routes for them.

Then we used the <Routes> component to make the group of all the routes. The <Routes> component is replacement of <Switch> component in react-router v6.

Then we used the <Route> to define each component with their path. You also may have noticed that we used the PublicRoute and PrivateRoute components to wrap the page components.

So here comes the magic, here you can define which components should be public, private, or restricted by wrapping them.

Let’s take an example of one route for /login path. So in the login route, we first defined the path of it and then wrap the <Login /> component in <PublicRoute> component.

The <PublicRoute> is the middleware of your appliaction and the <Login /> component is the children of it which you have return it in the Public and Private route components.

All Done!!!

Conclusion

So in this tutorial, you learned about what is the Public, Private and Restricted Routes components in react and how you can create and use them.

You learned how to protect the private page by checking the AUTH key from localStorage and redirecting to /login page and if the user logged in then redirect to the dashboard page.

Same for the public page, if the user tries to access the private page then redirect to the login page otherwise continue with the children’s components.

Photo of author

About Aman Mehra

Hey there! I'm Aman Mehra, a full-stack developer with over six years of hands-on experience in the industry. I've dedicated myself to mastering the ins and outs of PHP, WordPress, ReactJS, NodeJS, and AWS, so you can trust me to handle your web development needs with expertise and finesse. In 2021, I decided to share my knowledge and insights with the world by starting this blog. It's been an incredible journey so far, and I've had the opportunity to learn and grow alongside my readers. Whether you're a seasoned developer or just dipping your toes into the world of web development, I'm here to provide valuable content and solutions to help you succeed. So, stick around, explore the blog, and feel free to reach out if you have any questions or suggestions. Together, let's navigate the exciting world of web development!

Leave a Comment