I created a ProtectedRoute component:
import { getItem } from '~/utils/cookie';
import { ElementType } from 'react';
import { Navigate } from 'react-router-dom';
export const ProtectedRoute = ({
element: Component,
...rest
}: {
element: ElementType;
}) => {
const token = getItem('token');
return token ? <Component {...rest} /> : <Navigate to="/login" />;
};
export const getItem = (key: Key) => Cookies.get(key);
Usage of ProtectedRoute component:
{
path: '/profile',
element: <ProtectedRoute element={UserProfile} />
}
What are your opinions, how to properly handle whether the user is logged in, at the same time to make the code execution very fast and safe so that you don’t even feel the check?
Also as an option I used to call the context to decode the JWT token, and verify if it finds the user id inside. I gave up on calling the context because it takes a few milliseconds longer and sometimes loading the page seems buggy.