this is my 'routes.tsx' file where all i simply want to do is if user is not authenticated then he/she should not able to navigate into dashboard and other routes which will comes into app later. and if he is authenticated then he/she should not navigate to unauthenticated routes which are login , signup , confirm otp there could be more also. for now isAuthenticated function is only returning if local storage has token or not in boolean. this is also looks good but there are some issues in this code which i am facing like
- even after token is there in the local storage if user tries to navigate to any auth related route he is able to navigate there.
- one more thing which i want to implement here with 'axios' intercepter that if user manually removes token and then try to run any api then in the interceptor should check if local storage has no token then interceptor should clear storage and then navigate user back to the auth/login
expecting a simple and optimal flow for the authenticated and vice versa routes and with the interceptor 'axios' without refreshing app
import { Suspense } from "react";
import { Navigate, RouteObject } from "react-router-dom";
import { isAuthenticated } from "./auth";
import { Login, Dashboard, Signup, SendOTP } from "../pages";
import { AuthLayout, PrimaryLayout } from "../layouts";
export const routes: RouteObject[] = [
{
path: "/dashboard",
element: (
<Suspense fallback={<div>...LOADING</div>}>
{isAuthenticated() ? (
<PrimaryLayout />
) : (
<Navigate to="/auth/login" replace />
)}
</Suspense>
),
children: [
{
index: true,
element: <Dashboard />,
},
{ path: "*", element: <Navigate to="dashboard" replace /> },
],
},
{
path: "/auth",
element: <AuthLayout />,
children: [
{
index: true,
element: isAuthenticated() ? (
<Navigate to="/dashboard" replace />
) : (
<Navigate to="login" replace />
),
},
{
path: "login",
element: (
<Suspense fallback={<div>...LOADING</div>}>
<Login />
</Suspense>
),
},
{
path: "signup",
element: (
<Suspense fallback={<div>...LOADING</div>}>
<Signup />
</Suspense>
),
},
{
path: "confirm-otp",
element: (
<Suspense fallback={<div>...LOADING</div>}>
<SendOTP />
</Suspense>
),
},
{ path: "*", element: <Navigate to="/auth/login" replace /> },
],
},
{
path: "*",
element: isAuthenticated() ? (
<Navigate to="/dashboard" replace />
) : (
<Navigate to="/auth/login" replace />
),
},
];