In modern web applications, it's common to have certain pages or routes that should only be accessible to authenticated users. Implementing protected routes is a crucial aspect of securing your application and ensuring that sensitive information remains private.
This tutorial will guide you through the process of implementing protected routes in a React application using React Router for navigation and routing.
To implement protected routes, we need to create a higher-order component (HOC) or a custom hook that checks if a user is authenticated before rendering a specific route. If the user is not authenticated, they should be redirected to a login page or shown an error message.
First, let's set up a simple authentication state using React Context. This example assumes you have a basic understanding of how to use context in React.
// src/context/AuthContext.js
import React, { createContext, useState } from 'react';
const AuthContext = createContext();
export const AuthProvider = ({ children }) => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const login = () => {
setIsAuthenticated(true);
};
const logout = () => {
setIsAuthenticated(false);
};
return (
<AuthContext.Provider value={{ isAuthenticated, login, logout }}>
{children}
</AuthContext.Provider>
);
};
export default AuthContext;
Next, we'll create a ProtectedRoute component that checks the authentication status and renders the appropriate content.
// src/components/ProtectedRoute.js
import React from 'react';
import { Navigate } from 'react-router-dom';
import AuthContext from '../context/AuthContext';
const ProtectedRoute = ({ children }) => {
const { isAuthenticated } = React.useContext(AuthContext);
if (!isAuthenticated) {
return <Navigate to="/login" replace />;
}
return children;
};
export default ProtectedRoute;
Now, let's integrate the ProtectedRoute into your routing configuration.
// src/App.js
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import AuthProvider from './context/AuthContext';
import Login from './pages/Login';
import Dashboard from './pages/Dashboard';
import ProtectedRoute from './components/ProtectedRoute';
const App = () => {
return (
<AuthProvider>
<Router>
<Routes>
<Route path="/login" element={<Login />} />
<Route
path="/dashboard"
element={
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
}
/>
<Route path="*" element={<Navigate to="/login" replace />} />
</Routes>
</Router>
</AuthProvider>
);
};
export default App;
login and logout functions.<Navigate> component.ProtectedRoute to protect the /dashboard route.Let's create a simple login and dashboard page to demonstrate how this works.
// src/pages/Login.js
import React from 'react';
import AuthContext from '../context/AuthContext';
const Login = () => {
const { login } = React.useContext(AuthContext);
return (
<div>
<h2>Login</h2>
<button onClick={login}>Login</button>
</div>
);
};
export default Login;
// src/pages/Dashboard.js
import React from 'react';
const Dashboard = () => {
return (
<div>
<h2>Dashboard</h2>
<p>Welcome to your protected dashboard!</p>
</div>
);
};
export default Dashboard;
/dashboard./dashboard, you should see the protected dashboard content.In this tutorial, we covered how to implement protected routes in a React application using React Router and context for authentication state management. In the next section, we will explore handling forms in React, which is another essential aspect of building interactive web applications.
Feel free to experiment with different authentication mechanisms and routing configurations to suit your application's needs.