3

How to Create a Protected Route in React

 2 years ago
source link: https://www.makeuseof.com/create-protected-route-in-react/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How to Create a Protected Route in React

By Mary Gathoni

Published 14 hours ago

Preventing unauthorized users from accessing your React page is critical for security. Here's how to do it.

Protected routes are those routes that only grant access to authorized users. This means that users must first meet certain conditions before accessing that specific route. For instance, your application can require only logged-in users be able to visit the dashboard page.

In this tutorial, you are going to learn how you create protected routes in a React application.

Note that you will be using React Router v6, which is a bit different from previous versions.

Getting Started

To get started, use create-react-app to bootstrap a simple React application.

npx create-react-app protect-routes-react

Navigate to the folder that was just created and start your application.

cd protect-routes-react
npm start

Open your application folder with your preferred text editor and clean it up. Your app.js should look like this.

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

You are now ready to set up the routes.

Related: How to Create Your First React App With JavaScript

Setting Up the React Router

You will use React Router to set up the navigation for your application.

Install react-router-dom.

npm install react-router-dom

For this application, you will have three main pages:

  • Home page(the landing page).
  • Profile page (protected, so only logged-in users have access).
  • About page (public so anyone can access it).

In Navbar.js, use the Link component from react-router-dom to create the navigation links to various paths.

const { Link } = require("react-router-dom");
const Navbar = () => {
return (
<nav style={{ textAlign: "center", marginTop: "20px" }}>
<Link to="/" style={{ padding: "10px" }}>
Home
</Link>
<Link to="/profile" style={{ padding: "10px" }}>
Profile
</Link>
<Link to="/about" style={{ padding: "10px" }}>
About
</Link>
</nav>
);
};
export default Navbar;

In app.js create the routes matching the links in the navigation menu.

import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Navbar from "./Navbar";
import Home from "./Home";
import Profile from "./Profile";
import About from "./About";
function App() {
return (
<Router>
<Navbar />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/profile" element={<Profile />} />
<Route path="/about" element={<About />} />
</Routes>
</Router>
);
}
export default App;

Now you need to create the components you have referenced in App.js.

In Home.js:

const Home = () => {
return <h1>Home page</h1>;
};
export default Home;

In Profile.js

const Profile = () => {
return <h1 style={{ textAlign: "center" }}>Profile Page</h1>;
};
export default Profile;

In About.js

const About = () => {
return <h1 style={{ textAlign: "center" }}>About page</h1>;
};
export default About;

Creating Protected Routes in React

Next up is creating protected routes. The home and about routes are public meaning anyone can access them, but the profile route requires users to be authenticated first. Therefore, you need to create a way to log in users.

Setting Up Fake Authentication

Since this is not an authentication tutorial, you will use React useState hook to simulate a login system.

In App.js, add the following.

import { Routes, Route, BrowserRouter } from "react-router-dom";
import { useState } from "react";
// Other import stamements
function App() {
const [isLoggedIn, setisLoggedIn] = useState(null);
const logIn = () => {
setisLoggedIn(true);
};
const logOut = () => {
setisLoggedIn(false);
};
return (
<BrowserRouter>
<Navbar />
{isLoggedIn ? (
<button onClick={logOut}>Logout</button>
) : (
<button onClick={logIn}>Login</button>
)}
<Routes>
</Routes>
</BrowserRouter>
);
}
export default App;

Here, you are tracking the login status of the user using state. You have two buttons, the login, and the logout button. These buttons are rendered in turn depending on whether a user is logged in or not.

If the user is logged out, the login button is displayed. Clicking on it will trigger the login function which will update the isLoggedIn state to true and in turn the display from login to the logout button.

Related: What Is User Authentication and How Does It Work?

Protecting Private Components

To protect routes, the private components must also have access to the isLoggedIn value. You can do this by creating a new component that accepts the isLoggedIn state as a prop and the private component as a child.

For instance, if your new component is named "Protected", you would render a private component like this.

<Protected isLoggedIn={isLoggedIn}>
<Private/>
</Protected>

The Protected component will check whether isLoggedIn is true or false. If it's true, it will go ahead and return the Private component. If it's false, it will redirect the user to a page where they can log in.

Learn more about other ways you can use to render a component depending on conditions from this article on conditional rendering in React.

In your application, create Protected.js.

import { Navigate } from "react-router-dom";
const Protected = ({ isLoggedIn, children }) => {
if (!isLoggedIn) {
return <Navigate to="/" replace />;
}
return children;
};
export default Protected;

In this component, the if statement is used to check whether the user is authenticated. If they are not, Navigate from react-router-dom redirects them to the home page. However, if the user is authenticated, the child component is rendered.

Use Protected.js in App.js modify the Profile page route.

<Route
path="/profile"
element={
<Protected isLoggedIn={isLoggedIn}>
<Profile />
</Protected>
}
/>

App.js should look like this.

import { Routes, Route, BrowserRouter } from "react-router-dom";
import { useState } from "react";
import Navbar from "./Navbar";
import Protected from "./Protected";
import Home from "./Home";
import About from "./About";
import Profile from "./Profile";
function App() {
const [isLoggedIn, setisLoggedIn] = useState(null);
const logIn = () => {
setisLoggedIn(true);
};
const logOut = () => {
setisLoggedIn(false);
};
return (
<BrowserRouter>
<div>
<Navbar />
{isLoggedIn ? (
<button onClick={logOut}>Logout</button>
) : (
<button onClick={logIn}>Login</button>
)}
<Routes>
<Route path='/' element={<Home />} />
<Route path='/profile'
element={
<Protected isLoggedIn={isLoggedIn}>
<Profile />
</Protected>
}
/>
<Route path ='/about' element={<About />} />
</Routes>
</div>
</BrowserRouter>
);
}
export default App;

That's it on creating protected routes. You can now access the Profile page only if you are logged in. If you try to navigate to the Profile page without logging in you will be redirected to the home page.

Role-Based Access Control

This tutorial showed you how you can restrict unauthenticated users from accessing a page in a React application. In some cases, you might need to go even further and restrict users based on their roles. For instance, you can have a page say an analytics page that only grants access to admins. Here, you will need to add logic in the Protected component that checks whether a user meets the required conditions.

About The Author

61ea6a8349dc0-p2v702.jpg?fit=crop&w=100&h=100

Mary Gathoni (8 Articles Published)

Mary Gathoni is a software developer with a passion for creating technical content that is not only informative but also engaging. When she is not coding or writing, she enjoys hanging out with friends and being outdoors.

More From Mary Gathoni

Subscribe to our newsletter

Join our newsletter for tech tips, reviews, free ebooks, and exclusive deals!

Click here to subscribe

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK