Creating Protected Routes With React Router

blog-13-1.jpg

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 do 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:

What Are Protected Routes in React Router?

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 vs Authorization in React Apps

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.

Key Features of Protected Routes in React

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.

React Router Version Variations

1. React Router v5 (Older Version)
In v5, protected routes were usually created using the Route component along with the render or component prop. You had to manually check authentication inside these props and then redirect users if they were not logged in. This approach worked but required more boilerplate code.

2. React Router v6 (Latest Version)
In v6, the process is more straightforward and cleaner. Instead of render or component, v6 uses the element prop to load components. You can wrap protected routes inside a custom component that checks authentication and either shows the page or redirects the user to login.

3. Key Differences Between v5 and v6

  • In v5, you often wrote more code to handle redirects, while in v6 it’s simpler and requires fewer lines.
  • v6 removed Switch and replaced it with Routes, which makes the routing system easier to read and manage.
  • Protected routes in v6 are easier to organize because you can directly nest them inside Routes.

4. Which Version Should You Use?
If you are starting a new project, always go with React Router v6 because it is modern, well-supported, and much easier to handle protected routes. v5 is only useful if you are maintaining older projects.

Benefits of Protected Routes in React Applications

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.

Q6. What re protected routes in React and why use them?

Protected routes in React are routes that restrict access to certain pages based on conditions like authentication, ensuring only authorized users can view them.

Q7. How do I create protected routes with React Router v6?

You can create protected routes in React Router v6 by wrapping routes in a component that checks authentication and redirects unauthorized users.

Q8. What’s the difference between authentication and authorization?

Authentication verifies a user’s identity, while authorization determines what actions or resources the user is allowed to access.

Q9. How can I implement role-based protected routes (e.g., admin vs user)?

You can implement role-based protected routes by checking the user’s role from context or state and rendering routes conditionally based on their permissions.

Q10. Can I redirect users back to the original page after login?

Yes, you can redirect users back to the original page after login by storing their intended path and navigating them there post-authentication.

Q11. How to handle protected routes for async-auth (e.g., token check, API call)?

You can handle protected routes for async-auth by showing a loading state while verifying the token or API call before granting access.

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