React itself doesn't have middleware like Express.js. However, in React we simulate middleware-like behavior in certain areas like:
🔹 1. In Redux (or Redux Toolkit)
Redux allows middleware such as redux-thunk, redux-saga, or custom ones to intercept actions.
npm install redux redux-thunk
// store.js
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
const store = createStore(rootReducer, applyMiddleware(thunk));
✅ Example middleware:
const logger = store => next => action => {
console.log("Dispatching:", action);
return next(action);
};
🔹 2. Using useEffect for Middleware-Like Effects
In functional components, you can perform tasks like authentication, logging, or API calls using useEffect.
useEffect(() => {
// simulate middleware
if (!user.isAuthenticated) {
navigate('/login');
}
}, [user]);
🔹 3. React Router Middleware-like Guards
React Router v6 doesn't have middleware, but you can use wrapper components for route guarding:
function ProtectedRoute({ children }) {
const auth = useAuth();
return auth.user ? children : <Navigate to="/login" />;
}
Usage:
<Route path="/dashboard" element={<ProtectedRoute><Dashboard /></ProtectedRoute>} />
🔹 4. Axios Interceptors (Middleware for API requests)
You can intercept requests and responses:
axios.interceptors.request.use(config => {
config.headers.Authorization = `Bearer ${token}`;
return config;
});
✅ Summary:
| Use Case | Middleware Technique |
|---|---|
| Redux actions | redux-thunk, redux-saga |
| Route protection | Wrapper Components / Guards |
| Side effects / Auth | useEffect |
| API requests | Axios Interceptors |