JIYIK CN >

Current Location:Home > Learning > WEB FRONT-END > React >

React Router Authentication

Author:JIYIK Last Updated:2025/03/03 Views:

We will cover protected routes and authentication using react-router in React applications.

When building commercial web applications or websites in React, we often need to hide certain routes in the application from users who are not logged in or do not have a specific user role required to access those routes.

React Router provides us with protected routes; they let us choose which routes a user can access based on their role or whether they are logged in.

For example, we have a page that is accessible to all users home, aboutsuch as , , contactand login. But protected routes such as 仪表板and 配置文件设置can only be accessed by logged in users.

React Router doesn't provide any functionality for this, but adding this functionality is pretty simple and straight forward. First, we need to add functionality to authenticate users to start working with protected routes.

We will use a fake AuthUserHook to check the authentication status.

Let us create a new application using the following command.

# react
npx create-react-app my-app

After creating our new application in React, we will go to our application directory using this command.

# react
cd my-app

Now, let's run our application to check if all dependencies are installed correctly.

# react
npm start

We will srccreate a new file in the folder AuthUser.js. Once we have created a new file, we will now create a context and assign it to a constant authUserContext.

# react
const authUserContext = React.createContext();

Once we have created a context, we will now create a function AuthUserthat will set the state of two variables to true authenticateand setAuthenticatefalse, which we will use to check if the user is authenticated.

We'll create 2 methods that return login()and logout(). login()will setAuthenticateset the value of to true, and logout()will set it back to false.

Now, we will export the function AuthenticationProvider, which will AuthUser()be saved in a constant auth. So our AuthUser.jscode in will be as follows.

import * as React from "react";

const authUserContext = React.createContext();

function AuthUser() {
  const [authenticate, setAuthenticate] = React.useState(false);

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

export function AuthenticationProvider({ children }) {
  const auth = AuthUser();

  return (
    <authUserContext.Provider value={auth}>{children}</authUserContext.Provider>
  );
}

export default function AuthenticateConsumer() {
  return React.useContext(authUserContext);
}

Whenever we want to use authenticate, , login()and logout(), we can use AuthUserHooks. We will start building the navigation, which will contain 5 components Home, About, Profile, Login, and Dashboard.

Home, Aboutand Loginwill be publicly accessible, while Dashboardand Profilewill only be accessible if the user is authenticated.

First, we'll react-router-domimport Link, Routes, Route, UseNavigateand from userLocation. We'll also import from the new file we created AuthUser.

# react
import * as React from "react";
import {
  Link,
  Routes,
  Route,
  useNavigate,
  Navigate,
  useLocation
} from "react-router-dom";
import AuthUser from "./AuthUser";

Now we'll define constants for the navigation that appears when one of the navigation links is visited.

If it is a publicly accessible link, the public route will be displayed, if it is a private link, the private route will be displayed only if the user is authenticated. Otherwise, it will be redirected to the login page.

# react
const Home = () => <h1>Home (Public Route)</h1>;
const About = () => <h1>About (Public Route)</h1>;

const Dashboard = () => <h1>Dashboard (Private)</h1>;
const Profile = () => <h1>Profile (Private)</h1>;

Now we'll Logincreate a constant for the method, where we'll log the user in and redirect them to after authentication dashboard.

If the user is not logged in, it returns a login page content which will be displayed whenever an unauthenticated user tries to access a private page.

const Login = () => {
  const navigate = useNavigate();
  const { login } = AuthUser();
  const { state } = useLocation();

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

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

Now we will create a navigation function in which we will return a navigation bar with all the routes, both public and private, with a login button if the user is not authenticated and a logout button if the user is authenticated.

We will also create 2 methods, handleLogoutand handleLogin.

function Nav() {
  const { authenticate, logout, login } = AuthUser();
  const navigate = useNavigate();

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

  return (
    <nav>
      <ul>
        <li>
          <Link to="/">Home</Link>
        </li>
        <li>
          <Link to="/about">About</Link>
        </li>
        <li>
          <Link to="/dashboard">Dashboard</Link>
        </li>
        <li>
          <Link to="/profile">Profile</Link>
        </li>
        <li>{!authenticate && <button onClick={handleLogin}>Login</button>}</li>
      </ul>
      {authenticate && <button onClick={handleLogout}>Logout</button>}
    </nav>
  );
}

We will create a function RequireAuthenticationthat will authenticate the user whenever they try to access a private route.

function RequireAuthentication({ children }) {
  const { authenticate } = AuthUser();
  const location = useLocation();

  return authenticate === true ? (
    children
  ) : (
    <Navigate to="/login" replace state={{ path: location.pathname }} />
  );
}

In our App()function, we will define our routes.

export default function App() {
  return (
    <div>
      <Nav />

      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route
          path="/dashboard"
          element={
            <RequireAuthentication>
              <Dashboard />
            </RequireAuthentication>
          }
        />
        <Route
          path="/profile"
          element={
            <RequireAuthentication>
              <Profile />
            </RequireAuthentication>
          }
        />
        <Route path="/login" element={<Login />} />
      </Routes>
    </div>
  );
}

Let's test our application and check how it works. See the demo here .

Output:

React Router Authentication Example

As you can see in the example above, it's pretty easy to set up authenticated routes, but the AuthUserHook we're using is just a frontend check.

However, if we are developing a proper web application, we need to authenticate users on the backend to protect our system.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

React Tutorial - Transferring Props

Publish Date:2025/03/16 Views:188 Category:React

React transfers Props. Props are generated when components are encapsulated. Components expose some properties (Props) to the outside world to complete some functions.

React Tutorial: Props Anti-Pattern

Publish Date:2025/03/16 Views:187 Category:React

React's Props anti-pattern, using Props to generate state in getInitialState is an anti-pattern - Anti-Pattern.

React Tutorial - Props Validation

Publish Date:2025/03/16 Views:102 Category:React

Props validation is a very useful way to use components correctly. It can avoid many bugs and problems as your application becomes more and more complex. In addition, it can make your program more readable.

Why do you need to bind event handlers in React Class Components?

Publish Date:2025/03/16 Views:60 Category:React

When using React, we must have come across control components and event handlers. We need to use `.bind()` in the constructor of the custom component to bind these methods to the component instance. As shown in the following code:

Solution to the error "does not contain a default export" in React

Publish Date:2025/03/16 Views:191 Category:React

When we try to use `default import` to import from a module that does not have a `default export`, we get a "does not contain a default export" error. To fix the error, make sure the module has named exports and wrap the import in curly braces, e.g.

Solve the Module not found: Can't resolve 'react-bootstrap' error

Publish Date:2025/03/16 Views:90 Category:React

To resolve the error "Module not found: Error: Can't resolve 'react-bootstrap'", make sure to install the react-bootstrap package by opening a terminal in the root directory of the project and running the command `npm install react-bootstrap bootstrap

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial