Education

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

logo

DhiWise

September 19, 2022
image
Author
logo

DhiWise

{
September 19, 2022
}

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 = () => 

Home (Public)

; const About = () =>

About (Public)

; const Dashboard = () =>

Dashboard (Private)

; const Login = () =>

TODO

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

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 Log in button click login is called and upon the successful login, the user will navigate to the dashboard. 

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 (
    

Login

); };

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 (
    
  );
}

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


  } />
  } />
  
        
      
    }
  />
    } />

In the above code you can add more protected routes  inside the RequireAuth components similar to dashboard. The RequireAuth renders the child element only if they are authenticated otherwise it will be redirected 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. With the web builder, you can easily set navigation in and out using a visual programming language in a few simple steps.

Also, it allows you to pass the data from the current page to the page you are navigating via API response, Navigation arguments, and constant files. 

how-to-dhiwise

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.  

summer-sale

These are just a few capabilities of DhiWise Web builder. It offers you 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.