DEV Community

Prashant Sharma
Prashant Sharma

Posted on

A Guide to Creating Protected Routes with react-router-dom

Creating a simple protected routes setup with react-router-dom

Hello, Dev.to community! In today's tutorial, we'll explore a fundamental aspect of web development—protecting routes in your React application. We'll use the popular react-router-dom library to create secure, authenticated routes. By the end of this guide, you'll have a solid understanding of how to implement protected routes and enhance the security of your React app.

Let's dive in!

Setting Up Your React App

Before we get into protected routes, ensure you have a React app up and running. If not, create one using:

npx create-react-app protected-routes-app
cd protected-routes-app
Enter fullscreen mode Exit fullscreen mode

Now, install react-router-dom:

npm install react-router-dom
Enter fullscreen mode Exit fullscreen mode

Great! Let's move on to creating our protected route.

Understanding Protected Routes

Protected routes are crucial for limiting access to certain parts of your application to authenticated users only. They help ensure that sensitive information is accessible only to those who should see it.

In our case, we'll consider a scenario where we want to protect a dashboard route. Users should only access the dashboard if they are authenticated.

Implementing ProtectedRoute Component

Let's create a ProtectedRoute component that will serve as the gateway to our protected dashboard. This component will redirect users to a login page if they're not authenticated.

// ProtectedRoute.js
import React from 'react';
import { Route, Redirect } from 'react-router-dom';

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

export default ProtectedRoute;
Enter fullscreen mode Exit fullscreen mode

Implementing Authentication

Now, let's simulate authentication in our app. We'll create a simple AuthService that provides methods to log in and log out. This AuthService is just for explanation purpose, It is advised that you use a AuthContext or AuthReducer depending upon your choice and requirements.

// AuthService.js
class AuthService {
  static isAuthenticated = false;

  static login() {
    this.isAuthenticated = true;
  }

  static logout() {
    this.isAuthenticated = false;
  }
}

export default AuthService;
Enter fullscreen mode Exit fullscreen mode

Using ProtectedRoute in App.js

With our ProtectedRoute and AuthService ready, let's integrate them into our main App component.

// App.js
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import ProtectedRoute from './ProtectedRoute';
import AuthService from './AuthService';

const Dashboard = () => <h2>Dashboard</h2>;
const Login = () => <h2>Login</h2>;

const App = () => {
  return (
    <Router>
      <Switch>
        <Route path="/login" component={Login} />
        <ProtectedRoute
          path="/dashboard"
          component={Dashboard}
          isAuthenticated={AuthService.isAuthenticated}
        />
      </Switch>
    </Router>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Conclusion

Congratulations! You've successfully implemented protected routes in your React application using react-router-dom. This ensures that only authenticated users can access specific parts of your app, enhancing its overall security.

Feel free to customize this setup based on your authentication requirements or integrate it into existing projects. If you found this tutorial helpful, please consider giving it a like, sharing it with your fellow developers, and leaving any questions or comments below.

Happy coding!

Top comments (0)