Skip to content

Private Route

Implement Private Route on your React App

React Auth Kit has a RequireAuth functionality Based on React Router

RequireAuth is only available in react-auth-kit v2.x. It can be used with React Router v6. If you are using React Router v5, please use React-kuth-kit v1.x with PrivateRoute. Visit this page to know more.

Import

import { RequireAuth } from 'react-auth-kit'

Implementation

Add PrivateRoute in your Routes Files inside BrowserRouter or HashRouter

Demo

<BrowserRouter>
    <Routes>
      <Route path={'/secure'} element={
        <RequireAuth loginPath={'/login'}>
          <div>
            Secure
          </div>
        </RequireAuth>
      }/>
    </Routes>
</BrowserRouter>
Full Code
import React from "react"
import {BrowserRouter, Route} from "react-router-dom"
import {PrivateRoute} from 'react-auth-kit'
import SecureComponent from "./SecureComponent";

const Routes = () => {
  return (
    <BrowserRouter>
      <Routes>
        <Route path={'/login'} element={<Login/>}/>
        <Route path={'/secure'} element={
          <RequireAuth loginPath={'/login'}>
            <SecureComponent/>
          </RequireAuth>
        }/>
      </Routes>
    </BrowserRouter>
  )
}

Props

Name Type Required Description
loginPath string ✔ The fallback path, which will be used in case of the user is not authenticated
children React.Node ✔ The Component, which requires authentication

Added Prop: loginPath (Require): The fallback path, if the user is unauthorized.

— 🔑 —

React Auth Kit is Apache 2.0 License code