Protected Routes with ReactJS

Introduction

Protected routes are an essential part of any web application. They restrict access to certain parts of your application to authenticated users. In this blog post, we will learn how to create protected routes using ReactJS.

Prerequisites

Before we start, make sure you have the following:

  • Basic understanding of ReactJS

  • Node.js and npm installed on your computer

  • A text editor, like Visual Studio Code

Setting Up the Project

First, let’s set up a new ReactJS project. Open your terminal and run the following command:

npx create-react-app protected-routes

Then, navigate into your new project:

cd protected-routes

We will also need to install react-router-dom for routing:

npm install react-router-dom

Creating Basic Routes with React Router

React Router is a standard library for routing in React. Let’s create some basic routes. In your App.js, you might have something like this:

import React from 'react';

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

import Home from './Home';

import Dashboard from './Dashboard';


function App() {

  return (

    <Router>

      <Switch>

        <Route path="/" exact component={Home} />

        <Route path="/dashboard" component={Dashboard} />

      </Switch>

    </Router>

  );

}


export default App;


Here, we have two routes: a Home route and a Dashboard route.

Implementing Authentication

For simplicity, let’s mimic an authentication check with a function that returns true if the user is authenticated and false otherwise:

const isAuthenticated = () => {

    // logic to check if user is authenticated

    // return true or false

  };

In a real-world application, this could be checking if there’s a valid JWT in local storage.

Creating a Protected Route

Now, let’s create a higher-order component that checks if the user is authenticated:

import React from 'react';

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


const ProtectedRoute = ({ component: Component, ...rest }) => (

  <Route

    {...rest}

    render={props =>

      isAuthenticated() ? (

        <Component {...props} />

      ) : (

        <Redirect to="/login" />

      )

    }

  />

);


This ProtectedRoute component works just like the Route component, except it checks if the user is authenticated. If they are, it renders the Component. If not, it redirects the user to the /login page.

Testing the Protected Route

Finally, let’s use our ProtectedRoute component in App.js:

function App() {

    return (

      <Router>

        <Switch>

          <Route path="/" exact component={Home} />

          <ProtectedRoute path="/dashboard" component={Dashboard} />

        </Switch>

      </Router>

    );

  }

 

  export default App;

 

Now, if you try to navigate to /dashboard without being authenticated, you’ll be redirected to /login.

Conclusion

And that’s it! You’ve successfully created protected routes with ReactJS. This is a fundamental concept in web development and is crucial for creating secure web applications. Happy coding!

 

0 Comments