The route which a user cannot access without authorization is called as private route? A route is also called as private when there is access control like role-based login in a web application.
In this blog i wanted to focus on coding part instead on theory
// main.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './index.css';
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<AppRoutes />
</React.StrictMode>
);
//App.tsx
import React from 'react';
import { Outlet } from 'react-router-dom';
const App = () => <Outlet />;
// Approute.tsx
import { Navigate } from 'react-router-dom';
import { constants } from '@modules/dashboard/models/constants';
import { MasterLayout } from '../layout/masterlayout';
import LoginPage from './LoginPage'; // Assuming LoginPage component is already defined
import Home from './Home'; // Assuming Home component is already defined
import Customer from './Customer'; // Assuming Customer component is already defined
import Product from './Product'; // Assuming Product component is already defined
const AppRoutes = [
{
path: "/",
element: <App />,
children: [
{
path: "login",
element: <LoginPage />,
},
{
index: true,
element: <Navigate to="login" />,
},
{
path: "error/*",
element: <>Error page</>,
},
{
path: "logout",
element: <>Logout</>,
},
{
path: "/*",
element: <PrivateRoutes />,
children: [
{ path: "home", element: <Home /> },
{ path: "customer", element: <Customer /> },
{ path: "product", element: <Product /> },
],
},
],
},
];
const PrivateRoutes = () => {
const { TOKEN } = constants;
const isAuthenticated = localStorage.getItem(TOKEN);
if (!isAuthenticated) {
return <Navigate to="/login" replace />;
}
return (
<div>
<Navbar />
<SideBar />
<ContentWrapper>
<Outlet />
</ContentWrapper>
</div>
);
};
export { AppRoutes, PrivateRoutes };