How to Create React Private Route for Authenticated users(Route Guard)?

React-Router:

React Router is the standard routing library for React. “React Router keeps your UI in sync with the URL. It has a simple API with powerful features like lazy code loading, dynamic route matching, and location transition handling built right in. Make the URL your first thought, not an after-thought.”

import { BrowserRouter as Router,Switch,Route} from 'react-router-dom';
import Login from './components/Login';
import Dashboard from './components/Dashboard'

function App() {
  return (
  <Router>
     <Switch>
        <Route exact path="/" component={Login}/>
        <Route path="/login" component={Login}/>
        <Route path="/dashboard" component={Dashboard}/>
     </Switch>
</Router>);
}
export default App;

What is the issue with react Router?

React-router by default provides public routes. Perhaps there are situations where you want the routes are accessible to only authenticated users or make the routes available based on some business logic. In such a case private routes are the best.

To implement private-route we dont need a third party library ,we just need to create simple component that can handle the private route.

Private Route For Authenticated Users:

import React from 'react'
import {Route,Redirect} from 'react-router-dom'
import {useAuth} from '../contexts/AuthContext'

export default function PrivateRoute({component:Component,...rest}) {
    const {user} =useAuth();
    return (
        <Route {...rest} render={
            props=>{
                return user ? <Component {...props}/>:<Redirect to='/login'/>
            }
        }>
            
        </Route>
    )
}

Here useAuth is a custom hook that returns an authenticated user object(we can discuss this in another article), here if the user is authenticated then we have a user object,& hence it renders the child component provided in private route, else it redirects the user to login component.

import { BrowserRouter as Router,Switch,Route} from 'react-router-dom';
import Login from './components/Login';
import Dashboard from './components/Dashboard'
import PrivateRoute from './components/PrivateRoute'

function App() {
  return (
  <Router>
     <Switch>
        <Route exact path="/" component={Login}/>
        <Route path="/login" component={Login}/>Private
        <PrivateRoute path="/dashboard" component={Dashboard}/>
     </Switch>
</Router>);
}
export default App;

Hope you like the solution !!!

If you want the login,useAuth & dashboard components you can check my upcoming posts/tutorials on react firebase authentication.

Leave a Reply