Private (Protected) and Public Routes in Reactjs

Muhammad Umais Hassan
5 min readJul 24, 2021

--

In this article, we will learn about public and private routes in Reactjs.

Private and public routes

Why we use private and public routes?

To understand this let me explain two scenarios first which will help you to better understand the use of protected routes or public and private routes.

  1. Let suppose you have integrated authentications in your web application and you want to display your all other screens only when user is authenticated. If the user will try to access those screens which are private or protected he will automatically redirect to authentication screens. As, signin and signup pages are publically accessible to anyone without even authentication so for these we use Public routes.
  2. Now, in second scenario which is relevant to first one. Let say user is authenticated now in you web application and now all screens are visible and accessible by the user. But now as he is authenticated now so you will not want to show authentication screens because he is already authenticated so when user will try to access authentication screens (Sign in, Sign up screens) he will automatically redirect to home screen. For, this kind screens which are not accessible without authentication we use Private routes or Protected routes.

Hope you are now able to understand the need and use of private and public routes. So, lets move towards the coding part.

First of all create a react app and install react-router-dom library by using following commands

npx create-react-app appname

npm install react-router-dom

Now lets setup the folder structure. For this create a folder named “routes” inside your src folder. Then create PrivateRoute.js and PublicRoute.js files inside “routes” folder. Then create a folder named “pages” inside src folder and inside pages folder create Signin.js, Signup.js, Home.js files.

(Note: By the way you can use any kind of names for the folders and files but if you want to follow up this article specifically for learning purpose you should create exact folders like me it will help you to avoid any kind of errors)

Folder structure
Folder structure

Now lets make some changings in app.js file by creating routes inside so that we can navigate to different pages or screens. For, this first import BrowserRouter as Router, Switch and Route from react-router-dom library which we have just installed in our app.

import {BrowserRouter as Router, Switch, Route} from ‘react-router-dom’;

Then wrap whole app inside BrowserRouter (as Router) and create Routes for different pages (components) following a Switch wrapped around them which helps to switch the pages for respective URL address or path.

app.js

import React from "react";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import Home from "./Pages/Home";
import Signin from "./Pages/Signin";
import Signup from "./Pages/Signup";
const App = () => {
return (
<Router>
<Switch>
<Route path="/" component={Home} exact={true} />
<Route path="/signin" component={Signin} exact={true} />
<Route path="/signup" component={Signup} exact={true} />
</Switch>
</Router>
);
};
export default App;

This was the basic things that I am expecting that you know very well already because this article is not about the react basics so I am not going in depth of all these things. Now, lets move towards the main part which is working in PrivateRoute.js and PublicRoute.js files.

Private Route

In PrivateRoute.js we we will need some props first which we help to proceed further, so we will pass 3 props in it,

  1. isAuthenticated
  2. component
  3. restProps

isAuthenticated is a Boolean variable which we will use to check if the user is authenticated or not so it will contain true if user is authenticated and will contain false if the user is not authenticated

component is actually the name of component that user is trying to open

restProps variable contains all other props that we need in Route e.g. exact, etc.

Then we will apply an if else condition logic,

if (isAuthenticated) Show component

else redirect to authentication pages (signin page)

PrivateRoute.js

import React from "react";
import { Route, Redirect } from "react-router-dom";
const PrivateRoute = ({
isAuthenticated,
component: Component,
...restProps
}) => (
<Route
{...restProps}
component={(props) =>
isAuthenticated ? (
<Component {...props} />
) : (
<Redirect to="/signin" />
)
}
/>
);export default PrivateRoute;

Public Route

In public route we will again use same 3 props like we have used in private route, isAuthenticated, component, restProps.

The if condition logic will be a little bit of different here, as here we are going to make a logic for the user if he is already authenticated. So, we will redirect user to home page if he is authenticated and trying to access the authentication pages (signin or signup page).

if (isAuthenticated) redirect to home page

else show component

PublicRoute.js

import React from "react";
import { Route, Redirect } from "react-router-dom";
const PublicRoute = ({
isAuthenticated,
component: Component,
...restProps
}) => (
<Route
{...restProps}
component={(props) =>
isAuthenticated
? <Redirect to="/" />
: <Component {...props} />
}
/>
);export default PublicRoute;

Now finally we will replace routes that we were created in app.js file at start with our public and private routes.

app.js

import React, { useState } from "react";
import { BrowserRouter as Router, Switch } from "react-router-dom";
// Routes
import PrivateRoute from "./PrivateRoute";
import PublicRoute from "./PublicRoute";
// Pages
import Home from "./Pages/Home";
import Signin from "./Pages/Signin";
import Signup from "./Pages/Signup";
const App = () => { return(
const [isAuthenticated, setIsAuthenticated] = useState(false);

<Router>
<Switch>
<PrivateRoute
path="/"
isAuthenticated={isAuthenticated}
component={Home}
exact={true}
/>
<PublicRoute
path="/signin"
isAuthenticated={isAuthenticated}
component={Signin}
exact={true}
/>
<PublicRoute
path="/signup"
isAuthenticated={isAuthenticated}
component={Signup}
exact={true}
/>
</Switch>
</Router>
);
}
export default App;

Here we have replaced our home component Route with PrivateRoute because this component needs authentication for access. While signin and signup components do not need authentication so there routes we have replaced with PublicRoute. I have created a state named isAuthenticated which is by default set to false. You can handle this state later but for now to understand Public and Private routes working just change the value of isAuthenticated to true which means user is authenticated now and see the navigation results.

Just to avoid any confusion, protected and private routes are same things. As we use this route for those pages which we want to protect, without authentication their access is not possible so we can say them private as well. While public routes are those which any user can visit and view publically without even authentication.

This is all about Private Route and Public Route that you need to know. I hope this will be beneficial for you.

Happy Learning 😊

--

--