Zoom Webinar: Learn and enhance your TypeScript skills | 28th March 2023 | 10 AM PST [10:30 PM IST] Register here
Education

Protected Routes and Authentication: How to Create Protected Routes in React App?

logo

DhiWise

March 3, 2023
image
Author
logo

DhiWise

{
March 3, 2023
}

In the context of React web application, protected routes are those routes that only grant access permission to authorized users. For example, while making a login request for your social media account you need to provide an id and password to access a specific route. 

While building a web application you need to protect specific routes from users who don’t have authentication to access that route. The protected routes alias private routes help you to implement exactly that. It lets you choose the routes which users can visit based on whether they are logged in or not. 

In this article, we will learn how to create protected routes in the React web application all from scratch.

So let's get started with creating a React app.

Create React Application

Before creating a protected route we must have a React application already created and the components for which we are implementing the protected routes.  

// create a React application

npx create-react-app protect-routes-react

Navigate to the folder which you have just created and start your application.

cd protect-routes-react
npm start

Next, you need to open your application folder. Your app.js should look something like this.

// Empty React application

function App() {
 return 
; } export default App;

Use React Router 6.0 to set up navigation for your React app

Install the react-router-dom version 6. It is a standard library for routing in React that enables developers to navigate among views of various components in React app, change browser URLs, and keep the UI in synchronization with the URL.  

npm install react-router-dom@6

However before creating the protected routes, you should find out whether the user is authenticated. So let's create a way to log in users with the fake useAuth Hook and determine the user’s authentication status. This helps you to understand how to implement the useAuth Hook.

import * as React from "react";

const authContext = React.createContext();

function useAuth() {
  const [authed, setAuthed] = React.useState(false);

  return {
    authed,
    login() {
      return new Promise((res) => {
        setAuthed(true);
        res();
 });
    },
    logout() {
      return new Promise((res) => {
        setAuthed(false);
        res();
      });
    },
  };
}

export function AuthProvider({ children }) {
  const auth = useAuth();

  return {children};
}

export default function AuthConsumer() {
  return React.useContext(authContext);
}

Use the useAuth hook whenever you want to know whether the user is authenticated, login to a user account, or log out from the user account. The hook exposes the values from the library and enables any component to get the current authentication state and rerenders on the state changes. 

In this application, we will create the following three components:

  1. Home page: This will be our website landing page. 
  2. About page: Anyone can access the about page without authentication.
  3. Dashboard: This page will be protected so only logged-in users can access it.
  4. Login: The page will allow users to login into their account and will be publically accessible.

Let’s render the above routes through the following application






import * as React from "react";
import { Link, Routes, Route } from "react-router-dom";

const Home = () => <h1>Home (Public)</h1>;
const About = () => <h1>About (Public)</h1>;
const Dashboard = () => <h1>Dashboard (Private)</h1>;



const Login = () => <h1>TODO</h1>;

function Nav() {
  return (
    <nav>
      <ul>
        <li>
<Link to="/">Home</Link>
        </li>
        <li>
<Link to="/about">About</Link>
       </li>
      </ul>
    </nav>
  );
}

export default function App() {
  return (
      <div>
<Nav>
<Routes>
<Route path="/" 
element={<Home />} />
    <Route path="/about" 
element={<About />} />
<Route path="/dashboard" 
element={<Dashboard />} /> 
       <Route path="/login" 
element={<Login />} /> 
</Routes>
</div>
  );
}

At this point we are only mapping the app’s location to the few components. But how will you authenticate a user to Log in? Here, we need to build a Login component. 

Login Component: 

The Login component here renders a header and a button. On the Login button click login and the user will be navigated to the dashboard upon successful login. 

import { useNavigate } from "react-router-dom";
import useAuth from "./useAuth";

const Login = () => {
const navigate = useNavigate();
  const { login } = useAuth();

  const handleLogin = () => {
    login().then(() => {
      navigate("/dashboard");
    });
  };

  return (
    <div>
      <h1>Login</h1>
      <button onClick={handleLogin}>Log in</button>
    </div>
  );
};



Log Out Component:

Now, using the same useAuth hook creates the method to Logout.

import { useNavigate } from "react-router-dom";
import useAuth from "./useAuth";

function Nav() {
  const { authed, logout } = useAuth();
  const navigate = useNavigate();

  const handleLogout = () => {
    logout();
    navigate("/");
  };

  return (
    <nav>
      <ul>
        <li>
          <Link to="/">Home</Link>
        </li>
        <li>
          <Link to="/about">about</Link>
        </li>
      </ul>
      {authed && <button onClick={handleLogout}>Logout</button>}
    </nav>
  );
}

Next, we need to add protected routes to the dashboard, so only the authenticated users can access it. 

<Routes>
  <Route path="/" element={<Home />} />
  <Route path="/about" element={<Pricing />} />
  <Route
    path="/dashboard"
    element={
      <RequireAuth>
        <Dashboard />
      </RequireAuth>
    }
  />
    <Route path="/login" element={<Login />} />
</Routes>
;

In the above code you can add more protected routes inside the RequireAuth components similar to the dashboard. The RequireAuth renders the child element only if they are authenticated otherwise, it will be redirected back to the login page.

Here, the RequireAuth function will look something like this:

function RequireAuth({ children }) {
  const { authed } = useAuth();

  return authed === true ? children : ;
}

So, this is just one way to add protected routes to your React application. You can build a custom hook to add authentication and add multiple protected routes to your React application.

How DhiWise simplifies adding navigation and authentication in the React application

DhiWise React web application builder goes way further to simplify application development. The web builder lets you easily set navigation in and out using a visual programming language in a few simple steps.

sale-img

The social media authentication functionality in the app builder allows you to set up authentication using social media accounts so users do not have to set up and use an id and password. And they can easily sign up or log in using their social media accounts.

social-media

These are just a few capabilities of DhiWise web builder. It offers everything from design to code generation to UI customization to deployment. 

Click here to explore more about the platform and sign up now to start building your next React application with DhiWise.