In frameworks like Next.js, middleware can process API requests before they are sent to the server or after receiving the response. This allows for tasks like authentication, data transformation, and caching.
Example: Axios Middleware (Interceptors)
Using Axios interceptors, you can add middleware-like behavior for API calls.
import axios from 'axios';
// Create an Axios instance
const api = axios.create({
baseURL: 'https://api.example.com',
});
// Request interceptor
api.interceptors.request.use((config) => {
// Add authorization token to headers
const token = localStorage.getItem('authToken');
if (token) config.headers.Authorization = `Bearer ${token}`;
return config;
});
// Response interceptor
api.interceptors.response.use(
(response) => response, // Process successful response
(error) => {
if (error.response.status === 401) {
// Handle unauthorized access
window.location.href = '/login';
}
return Promise.reject(error);
}
);
export default api;