Creating Protected Routes With React Router

Creating Protected Routes With React Router

While building a web application, you might find a need for certain pages, like a dashboard or profile settings page, to be only visible to users when the user logs into your application, which means you should not want to provide access to each route to every user. That is the place where protected routes come into play. In this blog, you will get all the information about protected routes, how to create protected routes using react-router-dom, and why it is essential for building an application.

Table of Contents:

Protected Routes

A protected route is just a normal route (a defined path or URL endpoint) in your application, but with a lock on it, which means users who visit your application are not allowed to access certain routes unless they are an authenticated user (logged-in user).

For example, if someone visits your application (Employee Management System) and tries to go to the /dashboard page without logging in, then this is not a valid action, and the user quickly moves to the /login route. This is called protected routes, and making routes protected helps to keep your app safe and user-friendly.

Prerequisites

Before learning about the steps to create protected routes in React using react-router-dom, it’s important for us to understand react-router-dom and the basic definition of authorization and authentication.

What is React-Router-Dom?

The react-router-dom is an important library in React that allows you to perform navigation (the process of moving between different pages) and routing for single-page applications. It also helps you to create multiple pages (routes) in your React app. For example, you can create pages like /home, /about, and /login, etc, all without refreshing the page.

Master Skills And Build Real Projects.
Become a Web Developer
quiz-icon

Authentication and Authorization

When you are building a web application, two important concepts that everyone has to remember are Authentication and Authorization. Although they both sound similar, they are different. Let us understand both of these terms one by one:

Authentication is the process of verifying a user’s identity. It answers the question “Who are you?”. And the answer is given by users themselves when they are logging in and entering their email and password. If the provided information is correct, then the application considers them as authenticated users. Common methods of authentication used in web applications are traditional logins, social logins (like Google or Facebook), or token-based systems like JWT (JSON Web Tokens).

On the other hand, authorization is what an authenticated user is allowed to do. It answers the question, “What users are allowed to access?” For example, your application might have both regular and admin users. Admins have access to certain routes or features, such as the user management dashboard or advanced settings, that users don’t have. It ensures users can see the specific routes only and only if they have permission to see.

Features of Protected Routes

Here are some of the important features of protected routes:

  • Access Control: Protected routes help you to put restrictions on the routes so that only authorized users can access them.
  • Redirection: They automatically redirect users to the login page if they are not logged in.
  • Session Handling: It makes sure that only active sessions can access the sensitive data.
  • User Experience: It keeps your app clean and secure from unauthenticated users.

Creating Protected Routes by Using react-router-dom

If you want to create protected routes using React Router Dom, then you need to follow the following steps:

Step 1: Set up React Project

Setting up a React project on your system is very simple. For this, you need to open the command prompt and run the following code:

npm create vite@latest

Then, after running the command, type the name of the folder (protected-routes-intellipaat) and choose React as the library and JavaScript as the language, and then run the following command on the console one by one:

cd protected-routes-intellipaat
npm install
npm run dev

Step 2: Install the necessary libraries

Now, after setting up the React project successfully, you have to install the necessary library, that is, react-router-dom, for setting up the protected routes. Install it by writing the following command in the console:

npm install react-router-dom

Step 3: Create a ProtectedRoute Component

This component will check if the user is logged in or not. If they are not logged in, it sends them to the login page.

//ProtectedRoute.js

Reactjs

Step 4: Add Protected Routes to Your App

Here is how to make the ProtectedRoute component in your app routes:

//App.js

Reactjs

Step 5: Writing Other File Code and Folder Structure

Here, you are only making a dummy login file (doesn’t contain a login button and does not store any data). Let us see the code for the Dashboard.jsx and the Login.jsx.

//Dashboard.jsx

Reactjs

//Login.jsx

Reactjs

//Folder Structure

Project Folder Structure

Output:

Output React Project

Explanation: In the example, you are making the protected routes using react-router-dom. Now, if someone goes to /dashboard without being logged into your application, they will immediately be redirected to the /login route.

Benefits of Protected Routes

Here are some of the important benefits of making routes protected using the react-router-dom library:

  • Security: It helps to keep your website data secure because it prevents unauthorized users from accessing your website data.
  • Improved User Experience: Users can only see the things that they are allowed to see.
  • Scalability: Developers can easily add role-based access and permission control. which means you can make different routes for admin and normal users.
  • Code Reusability: Use the ProtectedRoute component across multiple areas of your application.

Get 100% Hike!

Master Most in Demand Skills Now!

Conclusion

Protected Routes is one of the most important concepts in React. It helps the developer to create secure web applications and improve the flow of the application. You can separate the routes for normal users and admins using protected routes. By understanding the basics of react-router-dom, you can easily make role-based routing and more for your web application.

Creating Protected Routes With React Router – FAQs

Q1. What is a React-Router-DOM?

The react-router-dom is an important library in React that helps you to create multiple pages (routes) for your React application and move between them without reloading the page.

Q2. What replaced React-Router-DOM?

The react-router-dom is still used in projects for navigation and routing. Because the latest version of react-router-dom (V6) has new features for making smooth web applications.

Q3. Is React Router DOM outdated?

No, it is one of the most commonly used libraries in modern React apps.

Q4. Should I learn React Router or Next.js?

React Router is used to build single-page applications, It is a library used with React and helpful in building client-side projects. But if you want to build a full-stack framework, then Next.js is a good option.

Q5. What is the difference between React Router DOM and Redux?

React Router is a utility library that is used for navigation and routing in a single-page application, while Redux is also a library that is used within React applications for managing app state.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner