Blog>
Snippets

Protecting Routes with Authentication Guards

Code example demonstrating how to create higher-order components (HOCs) for protecting routes that require user authentication.
import React from 'react';
import { Navigate } from 'react-router-dom';

// Function to check if the user is authenticated
const isAuthenticated = () => {
  // Ideally, replace the following with your authentication logic
  const user = localStorage.getItem('user');
  return !!user;
};

// Higher Order Component for protected routes
const withAuthProtection = (WrappedComponent) => {
  // Return a new component
  return (props) => {
    // Check for authentication
    if (!isAuthenticated()) {
      // Redirect to login page if not authenticated
      return <Navigate to='/login' />;
    }
    // Render the wrapped component if authenticated
    return <WrappedComponent {...props} />;
  };
};

export default withAuthProtection;
This piece of code defines a function `isAuthenticated` to check if a user is logged in, and a higher-order component (HOC) `withAuthProtection` which determines if the `WrappedComponent` should be rendered or if the user should be redirected to a login page.
import React from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import withAuthProtection from './withAuthProtection';
import Dashboard from './components/Dashboard';
import Login from './components/Login';

const App = () => (
  <Router>
    <Routes>
      <Route path='/login' element={<Login />} />
      // Protect the Dashboard route
      <Route path='/dashboard' element={withAuthProtection(Dashboard)} />
    </Routes>
  </Router>
);

export default App;
This part of the code uses the `withAuthProtection` HOC to protect the `/dashboard` route. Unauthenticated users will be redirected to `/login` when they try to access the dashboard.