Blog>
Snippets

Route Guards for Authentication

Create an example of a route guard that checks if a user is authenticated before allowing access to a protected route, redirecting to a login page if not authenticated.
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
Import necessary components from react and react-router-dom.
const isAuthenticated = () => {
    // Logic to check if the user is authenticated
    // It could be a check to localStorage, a context, or something else
    return localStorage.getItem('user') ? true : false;
};
Define a function to check if the user is authenticated. This is a placeholder that you should replace with your actual authentication logic.
const ProtectedRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => (
        isAuthenticated() ? (
            <Component {...props} />
        ) : (
            <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
        )
    )} />
);
Create a ProtectedRoute component that takes a component and other props. It renders the component if isAuthenticated returns true, otherwise redirects to the login page. This acts as the route guard.
<ProtectedRoute path='/protected' component={ProtectedComponent} />
Example usage of the ProtectedRoute component to protect a route. Replace 'ProtectedComponent' with your actual component that should be protected.