How to Create a Protected Route in React

Protected routes are these routes that solely grant entry to approved customers. Which means customers should first meet sure situations earlier than accessing that particular route. As an illustration, your utility can require solely logged-in customers be capable of go to the dashboard web page.

On this tutorial, you will learn the way you create protected routes in a React utility.

Observe that you can be utilizing React Router v6, which is a bit totally different from earlier variations.

Getting Began

To get began, use create-react-app to bootstrap a easy React utility.

npx create-react-app protect-routes-react

Navigate to the folder that was simply created and begin your utility.

cd protect-routes-react
npm begin

Open your utility folder along with your most well-liked textual content editor and clear it up. Your app.js ought to appear like this.

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

You are actually able to arrange the routes.

Associated: The way to Create Your First React App With JavaScript

Setting Up the React Router

You’ll use React Router to arrange the navigation on your utility.

Set up react-router-dom.

npm set up react-router-dom

For this utility, you should have three important pages:

  • Dwelling web page(the touchdown web page).
  • Profile web page (protected, so solely logged-in customers have entry).
  • About web page (public so anybody can entry it).

MAKEUSEOF VIDEO OF THE DAY

In Navbar.js, use the Hyperlink part from react-router-dom to create the navigation hyperlinks to varied paths.

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


In app.js create the routes matching the hyperlinks within the navigation menu.

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

Now it is advisable to create the parts you’ve referenced in App.js.

In Dwelling.js:

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

In Profile.js

const Profile = () => {
return <h1 model={{ textAlign: "middle" }}>Profile Web page</h1>;
};
export default Profile;

In About.js

const About = () => {
return <h1 model={{ textAlign: "middle" }}>About web page</h1>;
};
export default About;

Creating Protected Routes in React

Subsequent up is creating protected routes. The dwelling and about routes are public which means anybody can entry them, however the profile route requires customers to be authenticated first. Due to this fact, it is advisable to create a approach to log in customers.

Setting Up Pretend Authentication

Since this isn’t an authentication tutorial, you’ll use React useState hook to simulate a login system.

In App.js, add the next.

import { Routes, Route, BrowserRouter } from "react-router-dom";
import { useState } from "react";
// Different import stamements
operate 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;

Right here, you’re monitoring the login standing of the person utilizing state. You may have two buttons, the login, and the logout button. These buttons are rendered in flip relying on whether or not a person is logged in or not.

If the person is logged out, the login button is displayed. Clicking on it would set off the login operate which can replace the isLoggedIn state to true and in flip the show from login to the logout button.

Associated: What Is Person Authentication and How Does It Work?

Defending Non-public Elements

To guard routes, the personal parts should even have entry to the isLoggedIn worth. You are able to do this by creating a brand new part that accepts the isLoggedIn state as a prop and the personal part as a baby.

As an illustration, in case your new part is called “Protected”, you’ll render a non-public part like this.

<Protected isLoggedIn={isLoggedIn}>
<Non-public/>
</Protected>

The Protected part will verify whether or not isLoggedIn is true or false. If it is true, it would go forward and return the Non-public part. If it is false, it would redirect the person to a web page the place they’ll log in.

Study extra about different methods you should utilize to render a part relying on situations from this text on conditional rendering in React.

In your utility, create Protected.js.

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

On this part, the if assertion is used to verify whether or not the person is authenticated. If they don’t seem to be, Navigate from react-router-dom redirects them to the house web page. Nevertheless, if the person is authenticated, the kid part is rendered.

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

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

App.js ought to appear like this.

import { Routes, Route, BrowserRouter } from "react-router-dom";
import { useState } from "react";
import Navbar from "./Navbar";
import Protected against "./Protected";
import Dwelling from "./Dwelling";
import About from "./About";
import Profile from "./Profile";
operate 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='/' aspect={<Dwelling />} />
<Route path='/profile'
aspect={
<Protected isLoggedIn={isLoggedIn}>
<Profile />
</Protected>
}
/>
<Route path ='/about' aspect={<About />} />
</Routes>
</div>
</BrowserRouter>
);
}
export default App;


That is it on creating protected routes. Now you can entry the Profile web page solely if you’re logged in. In case you attempt to navigate to the Profile web page with out logging in you can be redirected to the house web page.

Position-Based mostly Entry Management

This tutorial confirmed you how one can limit unauthenticated customers from accessing a web page in a React utility. In some circumstances, you may must go even additional and limit customers primarily based on their roles. As an illustration, you’ll be able to have a web page say an analytics web page that solely grants entry to admins. Right here, you will want so as to add logic within the Protected part that checks whether or not a person meets the required situations.


Photo of code showing on a computer screen
The way to Implement Conditional Rendering in React.js (With Examples)

Conditional rendering is a helpful manner to enhance your app. Listed here are a collection of methods to make use of it.

Learn Subsequent


About The Creator

Leave a Comment