Blog>
Snippets

Redirecting Unauthenticated Users

Provide an example of redirecting users to a login page if they attempt to access an authenticated route without being logged in.
import { Navigate } from 'react-router-dom';
First, import Navigate from react-router-dom to programmatically navigate the user.
const PrivateRoute = ({ children }) => {
  const isAuthenticated = false; // Assume a logic to determine authentication
  return isAuthenticated ? children : <Navigate to="/login" replace />;
};
Define a PrivateRoute component. It checks if the user is authenticated. If not, it redirects to the login page.
// Usage inside App component
<PrivateRoute>
  <YourProtectedComponent />
</PrivateRoute>;
Wrap your protected component with PrivateRoute to enforce the redirect if the user is unauthenticated.