I am using react-router-dom for Routing in my react app. I now want to create a protected route so you can access certain pages only if you are logged in. But at the moment I can still access the protected pages and dont get redirected from the login page to the dashboard after loggin in
index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import {
BrowserRouter as Router,
Routes,
Route,
Navigate,
} from 'react-router-dom';
import axios from 'axios';
import { UserContextProvider } from './context/userContext';
import { ToastProvider } from './context/toastContext';
import { DialogProvider } from './context/dialogContext';
import ProtectedRoute from './components/protectedRoute';
import Register from './pages/auth/register';
import Profile from './pages/profile';
import Friends from './pages/friends';
import Notifications from './pages/notifications';
import Landingpage from './pages/landingpage';
import Dashboard from './pages/dashboard';
import Login from './pages/auth/login';
import './index.css';
const routes = [
{ path: '/home', element: Landingpage },
{ path: '/dashboard', element: Dashboard, protected: true },
{ path: '/login', element: Login },
{ path: '/register', element: Register },
{ path: '/profile', element: Profile, protected: true },
{ path: '/friends', element: Friends, protected: true },
{ path: '/notifications', element: Notifications, protected: true },
{ path: '/', element: Navigate, to: '/home' },
];
axios.defaults.baseURL = 'http://localhost:8000';
axios.defaults.withCredentials = true;
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<UserContextProvider>
<ToastProvider>
<DialogProvider>
<Router>
<Routes>
{routes.map((route, index) => {
if (route.protected) {
return (
<Route
key={index}
path={route.path}
element={
<ProtectedRoute
element={route.element}
/>
}
/>
);
}
return (
<Route
key={index}
path={route.path}
element={<route.element to={route.to} />}
/>
);
})}
</Routes>
</Router>
</DialogProvider>
</ToastProvider>
</UserContextProvider>
);
protectedRoute.jsx
import React, { useContext } from 'react';
import { Navigate } from 'react-router-dom';
import { UserContext } from '../context/userContext';
import { Loader } from 'lucide-react';
const ProtectedRoute = ({ element: Component, ...rest }) => {
const { user, loading } = useContext(UserContext);
if (loading) {
return (
<div className='flex items-center justify-center py-4'>
<Loader className='animate-spin mr-2' />
<span>Lädt...</span>
</div>
);
}
if (!user) {
return <Navigate to='/login' />;
}
return <Component {...rest} />;
};
export default ProtectedRoute;