React JS Private Route and Authenticated Routes
Route Guards and Authenticated Routes are concepts used to control access to certain parts of a React application based on authentication or other conditions. They help ensure that only authorized users can access specific routes.
Route Guards
Route Guards are mechanisms to restrict access to certain routes based on specific conditions. They often involve checking authentication status or user roles before allowing access to a route.
Implementing Route Guards
1. Basic Route Guard Implementation
You can create a higher-order component (HOC) or a custom component to protect routes. For example, you can create a PrivateRoute
component that checks if a user is authenticated before rendering a route.
Example:
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
const PrivateRoute = ({ component: Component, ...rest }) => {
const isAuthenticated = // logic to determine if user is authenticated
return (
<Route
{...rest}
render={props =>
isAuthenticated ? (
<Component {...props} />
) : (
<Redirect to="/login" />
)
}
/>
);
};
export default PrivateRoute;
Usage:
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import PrivateRoute from './PrivateRoute';
import Home from './Home';
import Dashboard from './Dashboard';
import Login from './Login';
function App() {
return (
<Router>
<Switch>
<Route exact path="/login" component={Login} />
<PrivateRoute path="/dashboard" component={Dashboard} />
<Route path="/" component={Home} />
</Switch>
</Router>
);
}
export default App;
In this example:
PrivateRoute
checks if the user is authenticated. If not, it redirects them to the login page.- If the user is authenticated, it renders the requested component.
2. Using useNavigate
Hook for Redirection
In React Router v6, you can use the useNavigate
hook to programmatically navigate and handle redirection based on conditions.
Example:
import React from 'react';
import { useNavigate } from 'react-router-dom';
const ProtectedPage = () => {
const navigate = useNavigate();
const isAuthenticated = // logic to determine if user is authenticated
React.useEffect(() => {
if (!isAuthenticated) {
navigate('/login'); // Redirect to login if not authenticated
}
}, [isAuthenticated, navigate]);
return <div>Protected Content</div>;
};
export default ProtectedPage;
Authenticated Routes
Authenticated Routes are routes that should only be accessible to users who have successfully logged in or meet certain criteria. They often require integrating route guards to ensure that only authorized users can access them.
Implementing Authenticated Routes
1. Protecting Routes Based on Authentication
You can use the same PrivateRoute
pattern mentioned earlier to protect authenticated routes.
Example:
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
const AuthenticatedRoute = ({ component: Component, ...rest }) => {
const isAuthenticated = // logic to determine if user is authenticated
return (
<Route
{...rest}
render={props =>
isAuthenticated ? (
<Component {...props} />
) : (
<Redirect to="/login" />
)
}
/>
);
};
export default AuthenticatedRoute;
2. Handling User Roles
You might also want to handle different user roles or permissions. This involves checking the user’s role and conditionally rendering routes based on that.
Example:
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
const RoleBasedRoute = ({ component: Component, requiredRole, ...rest }) => {
const userRole = // logic to determine the user's role
const isAuthenticated = // logic to determine if user is authenticated
return (
<Route
{...rest}
render={props =>
isAuthenticated && userRole === requiredRole ? (
<Component {...props} />
) : (
<Redirect to="/unauthorized" />
)
}
/>
);
};
export default RoleBasedRoute;
Usage:
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import RoleBasedRoute from './RoleBasedRoute';
import AdminDashboard from './AdminDashboard';
import Unauthorized from './Unauthorized';
function App() {
return (
<Router>
<Switch>
<Route path="/unauthorized" component={Unauthorized} />
<RoleBasedRoute path="/admin" component={AdminDashboard} requiredRole="admin" />
{/* Other routes */}
</Switch>
</Router>
);
}
export default App;
Summary
Route Guards: Control access to routes based on conditions like authentication status. Use components like
PrivateRoute
orRoleBasedRoute
to protect routes.Authenticated Routes: Ensure that only logged-in users or users with specific roles can access certain routes. Implement this by checking authentication and role status before rendering the route.
These techniques help in creating secure and well-structured React applications, ensuring that users have the appropriate access based on their authentication and roles.