How to handle protected routes in React plus redirect user to original URL being visited

Handling Protected Routes in React and Redirecting Users

Protected routes are a crucial part of any web application that requires authentication. In React, we can use Higher Order Components (HOCs) to protect certain routes that require authentication.

Step 1: Create a Protected Route Component

We can create a component that checks if the user is authenticated and redirects them to a login page if they are not.


import React from 'react';
import { Route, Redirect } from 'react-router-dom';

const ProtectedRoute = ({ component: Component, isAuthenticated, ...rest }) => (
  <Route {...rest} render={(props) => (
    isAuthenticated === true
      ? <Component {...props} />
      : <Redirect to='/login' />
  )} />
);

export default ProtectedRoute;

In the above code, we are creating a component called ProtectedRoute. It takes in a component prop, which is the component that we want to protect. It also takes in an isAuthenticated prop, which is a boolean value that determines if the user is authenticated or not. The ...rest parameter spreads any additional props that we pass into the component.

We are using the Route component from react-router-dom to render our component. The render method takes in a function that returns the component if the user is authenticated or redirects them to the login page if they are not.

Step 2: Protect Your Routes

We can now use our ProtectedRoute component to protect any routes that require authentication.


import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

import Home from './components/Home';
import Dashboard from './components/Dashboard';
import Login from './components/Login';
import ProtectedRoute from './components/ProtectedRoute';

const App = () => {
  const [isAuthenticated, setIsAuthenticated] = React.useState(false);

  return (
    <Router>
      <div className="App">
        <Switch>
          <Route exact path="/" component={Home} />
          <ProtectedRoute
            exact
            path="/dashboard"
            component={Dashboard}
            isAuthenticated={isAuthenticated}
          />
          <Route exact path="/login" render={(props) => (
            <Login {...props} setIsAuthenticated={setIsAuthenticated} />
          )} />
        </Switch>
      </div>
    </Router>
  );
}

export default App;

In the above code, we are protecting the /dashboard route by using our ProtectedRoute component. We are passing in the isAuthenticated prop, which is set to false by default.

We are also passing in the setIsAuthenticated prop to our Login component. This allows us to set the isAuthenticated state to true once the user has successfully logged in.

Step 3: Redirecting Users to Original URL

If the user is redirected to the login page, we want to redirect them back to the original URL that they were trying to access after they have successfully logged in.

We can achieve this by storing the original URL in the session storage when the user is redirected to the login page. Once the user has successfully logged in, we can redirect them back to the original URL.


// Login component
const Login = ({ setIsAuthenticated, history }) => {
  const [username, setUsername] = React.useState('');
  const [password, setPassword] = React.useState('');

  const handleSubmit = (e) => {
    e.preventDefault();

    // Authenticate user
    setIsAuthenticated(true);

    // Get original URL from session storage
    const originalUrl = sessionStorage.getItem('originalUrl');

    // Redirect user to original URL
    if (originalUrl) {
      sessionStorage.removeItem('originalUrl');
      history.push(originalUrl);
    } else {
      history.push('/dashboard');
    }
  }

  return (
    <div className="login">
      <form onSubmit={handleSubmit}>
        <input type="text" placeholder="Username" value={username} onChange={(e) => setUsername(e.target.value)} />
        <input type="password" placeholder="Password" value={password} onChange={(e) => setPassword(e.target.value)} />
        <button type="submit">Login
      </form>
    </div>
  );
}

In the above code, we are getting the original URL from session storage using sessionStorage.getItem('originalUrl'). We are then removing the item from session storage using sessionStorage.removeItem('originalUrl') and redirecting the user back to the original URL using history.push(originalUrl).

We can store the original URL in session storage using sessionStorage.setItem('originalUrl', window.location.pathname) when the user is redirected to the login page.

Conclusion

In this article, we looked at how to handle protected routes in React and redirect users to the original URL after they have successfully logged in. We used Higher Order Components (HOCs) to protect certain routes that require authentication and stored the original URL in session storage to redirect the user back to the original URL after they have successfully logged in.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe