Creating Protected Routes with React Router: A 2026 Guide
Learn how to create protected routes in React applications using react-router-dom and Context API. This guide ensures secure navigation for authenticated users.
Creating Protected Routes with React Router: A 2026 Guide
In this tutorial, you'll learn how to create a protected route using react-router-dom in a React application. We will also utilize the Context API to manage and store user authentication states in localStorage, allowing users to maintain their login state even after refreshing the page or reopening the browser. This ensures that, post-login, users are redirected to a dashboard page, enhancing the user experience by providing seamless access to protected resources.
Key Takeaways
- Understand the concept of protected routes in React applications.
- Learn to manage authentication states using Context API and
localStorage. - Implement a redirect mechanism post-login to a dashboard.
- Utilize
react-router-domeffectively for route management.
Prerequisites
Before diving into this tutorial, ensure you have the following:
- Basic knowledge of React and JavaScript.
- Node.js and npm installed on your development machine.
- Experience with
react-router-domand Context API is beneficial but not required. - A text editor such as VSCode.
Step 1: Setting Up the React Application
First, create a new React application using Create React App. Open your terminal and run the following command:
npx create-react-app protected-routes-tutorialNavigate into your project directory:
cd protected-routes-tutorialNext, install react-router-dom for routing purposes:
npm install react-router-dom@6Step 2: Creating the Context API for Authentication
We'll use the Context API to manage authentication states. Create a new folder named context in the src directory and add a file named AuthContext.js:
import React, { createContext, useState, useEffect } from 'react';
const AuthContext = createContext();
const AuthProvider = ({ children }) => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
useEffect(() => {
const storedAuth = localStorage.getItem('isAuthenticated');
if (storedAuth) {
setIsAuthenticated(JSON.parse(storedAuth));
}
}, []);
const login = () => {
setIsAuthenticated(true);
localStorage.setItem('isAuthenticated', true);
};
const logout = () => {
setIsAuthenticated(false);
localStorage.removeItem('isAuthenticated');
};
return (
{children}
);
};
export { AuthContext, AuthProvider };This context provides login and logout functions and stores authentication state in localStorage to persist across sessions.
Step 3: Implementing Protected Routes
We will now create a component for protected routes. This component will check the authentication state and determine if the user can access a particular route. Create a new file ProtectedRoute.js in the src folder:
import React, { useContext } from 'react';
import { Route, Navigate } from 'react-router-dom';
import { AuthContext } from './context/AuthContext';
const ProtectedRoute = ({ children, ...rest }) => {
const { isAuthenticated } = useContext(AuthContext);
return (
}
/>
);
};
export default ProtectedRoute;This component uses the Context API to determine if a user is authenticated. If not, it redirects them to the login page.
Step 4: Creating the Route Structure
Let’s set up our routing structure. Edit the App.js file:
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import { AuthProvider } from './context/AuthContext';
import ProtectedRoute from './ProtectedRoute';
import LoginPage from './pages/LoginPage';
import DashboardPage from './pages/DashboardPage';
function App() {
return (
} />
}
/>
);
}
export default App;Here, we wrap our application in the AuthProvider to provide authentication context globally. The ProtectedRoute ensures only authenticated users access the DashboardPage.
Step 5: Implementing the Login Page
Create a login page where users can authenticate themselves. Add a new file LoginPage.js in the pages directory:
import React, { useContext } from 'react';
import { AuthContext } from '../context/AuthContext';
import { useNavigate } from 'react-router-dom';
const LoginPage = () => {
const { login } = useContext(AuthContext);
const navigate = useNavigate();
const handleLogin = () => {
login();
navigate('/dashboard');
};
return (
Login Page
Login
);
};
export default LoginPage;The login page provides a simple button that, when clicked, authenticates the user and redirects them to the dashboard.
Step 6: Creating the Dashboard Page
Create a DashboardPage.js file in the pages directory. This page will be protected and only accessible to authenticated users:
import React, { useContext } from 'react';
import { AuthContext } from '../context/AuthContext';
const DashboardPage = () => {
const { logout } = useContext(AuthContext);
return (
Dashboard
Logout
);
};
export default DashboardPage;This dashboard page includes a logout button, allowing users to terminate their session and clear authentication data from localStorage.
Common Errors/Troubleshooting
- Issue: User not redirected to the dashboard after login.
Solution: Ensure theloginfunction is correctly settingisAuthenticatedand updatinglocalStorage. - Issue:
ProtectedRoutenot working as expected.
Solution: Verify that theAuthContextis correctly providing theisAuthenticatedstate. - Issue: Errors with
useNavigate.
Solution: Ensure you have installed the correct version ofreact-router-dom(version 6 or higher).
Frequently Asked Questions
What is a protected route in React?
A protected route is a route that only authorized users can access. It ensures that only users who are logged in can view certain pages, enhancing security.
How does react-router-dom help in routing?
React-router-dom provides flexible routing capabilities in React applications, allowing developers to define routes and manage navigation seamlessly.
Why use Context API for authentication?
The Context API provides a way to share state globally across a React application, making it ideal for managing authentication states and user information.