JavaScript and React course ยท Module 6: React Router
Protecting Routes in the Space Station
In this lesson9
In different sectors of our space station, we need different access levels. Not every crew member should have access to all areas - similarly in web applications, where some pages should be accessible only to logged-in users or people with specific permissions.
What are Protected Routes?
Protected routes are a mechanism that allows restricting access to certain parts of the application only to authorized users. They are usually implemented by checking whether the user is logged in or has the appropriate permissions.
Basic Implementation of a Protected Route
The simplest way to protect a route is by using a higher-order component (HOC) that checks the authentication state:
import { Navigate, useLocation } from 'react-router-dom';
import { useAuth } from './AuthContext';
function ProtectedRoute({ children }) {
const { user, isLoading } = useAuth();
const location = useLocation();
// Show loading indicator while checking authentication state
if (isLoading) {
return <div className="loading">Checking section permissions...</div>;
}
// If the user is not logged in, redirect to the login page
if (!user) {
// Save the path the user came from so we can return after login
return <Navigate to="/login" state={{ from: location.pathname }} replace />;
}
// If the user is logged in, render the protected content
return children;
}Then we can use this component in our routes:
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/login" element={<LoginPage />} />
{/* Protected routes */}
<Route path="/command-center" element={
<ProtectedRoute>
<CommandCenter />
</ProtectedRoute>
} />
<Route path="/restricted-area" element={
<ProtectedRoute>
<RestrictedArea />
</ProtectedRoute>
} />
</Routes>Authentication Context
For the above code to work, we need an authentication context that will store information about the logged-in user:
import { createContext, useContext, useState, useEffect } from 'react';
const AuthContext = createContext(null);
export function AuthProvider({ children }) {
const [user, setUser] = useState(null);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
// Check if the user is already logged in (e.g., via a token in localStorage)
const checkAuthStatus = async () => {
try {
setIsLoading(true);
const token = localStorage.getItem('authToken');
if (token) {
// Token validation on the server or JWT decoding
const userData = await validateToken(token); // function implemented separately
setUser(userData);
}
} catch (error) {
console.error('Authentication error:', error);
// In case of error, log out the user
localStorage.removeItem('authToken');
setUser(null);
} finally {
setIsLoading(false);
}
};
checkAuthStatus();
}, []);
// Login and logout functions
const login = async (credentials) => {
setIsLoading(true);
try {
// Call login API
const response = await apiLogin(credentials);
const { token, user: userData } = response;
// Save the token
localStorage.setItem('authToken', token);
setUser(userData);
return true;
} catch (error) {
console.error('Login error:', error);
return false;
} finally {
setIsLoading(false);
}
};
const logout = () => {
localStorage.removeItem('authToken');
setUser(null);
};
return (
<AuthContext.Provider value={{ user, isLoading, login, logout }}>
{children}
</AuthContext.Provider>
);
}
// Hook for easy access to the authentication context
export function useAuth() {
return useContext(AuthContext);
}Redirect After Login
On the login page, we can use information about the previous path to redirect the user back after logging in:
import { useLocation, useNavigate } from 'react-router-dom';
import { useAuth } from './AuthContext';
import { useState } from 'react';
function LoginPage() {
const { login } = useAuth();
const navigate = useNavigate();
const location = useLocation();
// Get the path the user was redirected from (if it exists)
const from = location.state?.from || '/command-center';
const [credentials, setCredentials] = useState({
username: '',
password: ''
});
const handleChange = (e) => {
const { name, value } = e.target;
setCredentials(prev => ({
...prev,
[name]: value
}));
};
const handleSubmit = async (e) => {
e.preventDefault();
const success = await login(credentials);
if (success) {
// Redirect back to the protected path
navigate(from, { replace: true });
}
};
return (
<div className="login-container">
<h1>Space Station Access Center</h1>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="username">Astronaut ID:</label>
<input
id="username"
name="username"
type="text"
value={credentials.username}
onChange={handleChange}
required
/>
</div>
<div className="form-group">
<label htmlFor="password">Access Code:</label>
<input
id="password"
name="password"
type="password"
value={credentials.password}
onChange={handleChange}
required
/>
</div>
<button type="submit" className="login-button">
Gain Access
</button>
</form>
</div>
);
}Protecting Routes Based on Roles
We often need more complex logic than just checking if the user is logged in. For example, it may be necessary to check if the user has the appropriate role:
function RoleProtectedRoute({ children, requiredRoles = [] }) {
const { user, isLoading } = useAuth();
const location = useLocation();
if (isLoading) {
return <div className="loading">Checking permissions...</div>;
}
// Check if the user is logged in
if (!user) {
return <Navigate to="/login" state={{ from: location.pathname }} replace />;
}
// Check if the user has the required role
const hasRequiredRole = requiredRoles.length === 0 ||
requiredRoles.some(role => user.roles.includes(role));
if (!hasRequiredRole) {
return <Navigate to="/unauthorized" replace />;
}
return children;
}
// Usage:
<Route
path="/engine-room"
element={
<RoleProtectedRoute requiredRoles={['engineer', 'captain']}>
<EngineRoom />
</RoleProtectedRoute>
}
/>Organizing the Protected Section of the Application
A good practice is to group all protected routes in one place, which makes them easier to manage:
function AppRoutes() {
return (
<Routes>
{/* Public paths */}
<Route path="/" element={<HomePage />} />
<Route path="/login" element={<LoginPage />} />
<Route path="/register" element={<RegisterPage />} />
<Route path="/about" element={<AboutPage />} />
{/* Protected section */}
<Route path="/dashboard" element={<ProtectedRoute><DashboardLayout /></ProtectedRoute>}>
<Route index element={<Overview />} />
<Route path="profile" element={<Profile />} />
<Route path="settings" element={<Settings />} />
{/* Routes for engineers */}
<Route path="maintenance" element={
<RoleProtectedRoute requiredRoles={['engineer']}>
<MaintenancePanel />
</RoleProtectedRoute>
} />
{/* Routes for captains */}
<Route path="command" element={
<RoleProtectedRoute requiredRoles={['captain']}>
<CommandCenter />
</RoleProtectedRoute>
} />
</Route>
{/* Error handling */}
<Route path="/unauthorized" element={<UnauthorizedPage />} />
<Route path="*" element={<NotFoundPage />} />
</Routes>
);
}In the example above, we use nested routes where the main DashboardLayout component is protected, and all routes nested within it are automatically protected. Additionally, some routes have extra role-based protections.
Advanced Techniques
Lazy Loading for Protected Routes
We can combine route protection with lazy loading to improve application performance:
import { lazy, Suspense } from 'react';
// Lazy loading components
const CommandCenter = lazy(() => import('./CommandCenter'));
const MaintenancePanel = lazy(() => import('./MaintenancePanel'));
// In routing:
<Route path="command" element={
<RoleProtectedRoute requiredRoles={['captain']}>
<Suspense fallback={<Loading />}>
<CommandCenter />
</Suspense>
</RoleProtectedRoute>
} />Remembering Multiple Routes
Sometimes a user may try to access multiple protected routes before logging in. We can remember more than one route:
function useRedirectHistory() {
const [history, setHistory] = useState([]);
const addToHistory = (path) => {
setHistory(prev => {
// Avoid duplicates
if (!prev.includes(path)) {
return [...prev, path].slice(-5); // Keep only the last 5 paths
}
return prev;
});
};
const getLastPath = () => history[history.length - 1] || '/dashboard';
return { addToHistory, getLastPath };
}Handling Session Expiration
An important aspect of route protection is handling session expiration:
function useSessionExpiration() {
const { logout } = useAuth();
const navigate = useNavigate();
useEffect(() => {
// Handle JWT token expiration
const checkTokenExpiration = () => {
const token = localStorage.getItem('authToken');
if (token) {
try {
const payload = JSON.parse(atob(token.split('.')[1]));
const expirationTime = payload.exp * 1000; // Convert to milliseconds
if (Date.now() >= expirationTime) {
logout();
navigate('/login', {
state: {
message: 'Your session has expired. Please log in again.'
}
});
}
} catch (e) {
console.error('Token validation error:', e);
logout();
}
}
};
const interval = setInterval(checkTokenExpiration, 60000); // Check every minute
return () => clearInterval(interval);
}, [logout, navigate]);
}Summary
Protecting routes in React Router is a key aspect of creating secure applications. The main techniques include:
- Creating higher-order components (HOC) to protect routes
- Using React Context to manage authentication state
- Redirecting users to the login page while remembering the original path
- Implementing role-based access control
- Organizing the application structure with a clear division into public and protected sections
- Handling session expiration and automatic logout
Remember that client-side (browser) security should never be the only layer of protection. It should always be supplemented with proper server-side security, which should independently verify user permissions before providing access to protected resources.
Code for this lesson: App.jsx
import React, { useState, createContext, useContext } from 'react';
import { BrowserRouter, Routes, Route, Link, Navigate, useNavigate, useLocation } from 'react-router-dom';
// Authorization context
const AuthContext = createContext();
function AuthProvider({ children }) {
const [user, setUser] = useState(null);
const login = (username) => {
setUser({ name: username, role: 'astronaut' });
};
const logout = () => {
setUser(null);
};
return (
<AuthContext.Provider value={{ user, login, logout }}>
{children}
</AuthContext.Provider>
);
}
function useAuth() {
return useContext(AuthContext);
}
// Protected Route component
function ProtectedRoute({ children }) {
const { user } = useAuth();
const location = useLocation();
if (!user) {
// Redirect to login while saving the location
return <Navigate to="/login" state={{ from: location }} replace />;
}
return children;
}
// Login page
function LoginPage() {
const [username, setUsername] = useState('');
const { login } = useAuth();
const navigate = useNavigate();
const location = useLocation();
const from = location.state?.from?.pathname || '/dashboard';
const handleSubmit = (e) => {
e.preventDefault();
if (username.trim()) {
login(username);
navigate(from, { replace: true });
}
};
return (
<div className="page login">
<h1>Login</h1>
<form onSubmit={handleSubmit}>
<input
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="Username"
/>
<button type="submit">Log in</button>
</form>
<p className="info">Log in to access protected sections.</p>
</div>
);
}
// Public page
function HomePage() {
return (
<div className="page">
<h1>Public page</h1>
<p>This page is accessible to everyone.</p>
</div>
);
}
// Protected page
function DashboardPage() {
const { user, logout } = useAuth();
const navigate = useNavigate();
const handleLogout = () => {
logout();
navigate('/');
};
return (
<div className="page dashboard">
<h1>Dashboard</h1>
<p>Welcome, {user?.name}! This is a protected page.</p>
<button onClick={handleLogout} className="logout">Log out</button>
</div>
);
}
// Secret page
function SecretPage() {
return (
<div className="page secret">
<h1>Secret page</h1>
<p>Congratulations! You have access to classified data.</p>
</div>
);
}
// Navigation
function Navigation() {
const { user } = useAuth();
return (
<nav>
<Link to="/">Home</Link>
{user ? (
<>
<Link to="/dashboard">Dashboard</Link>
<Link to="/secret">Secret</Link>
<span className="user-info">{user.name}</span>
</>
) : (
<Link to="/login">Log in</Link>
)}
</nav>
);
}
function App() {
return (
<AuthProvider>
<BrowserRouter>
<div className="app">
<Navigation />
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/login" element={<LoginPage />} />
<Route
path="/dashboard"
element={
<ProtectedRoute>
<DashboardPage />
</ProtectedRoute>
}
/>
<Route
path="/secret"
element={
<ProtectedRoute>
<SecretPage />
</ProtectedRoute>
}
/>
</Routes>
</div>
</BrowserRouter>
</AuthProvider>
);
}
export default App;Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. How does NavLink in React Router allow you to dynamically set a CSS class based on the active state?
Hands-on tasks in the game
- Horizontal ordering
Arrange the Link component syntax elements:
- Click in order
Arrange the NavLink with a dynamic class: