Blog>
Snippets

Network Request Timing with Axios Interceptors

Utilize Axios interceptors to measure and log the duration of HTTP network requests in a Next.js application.
import axios from 'axios';

// Create an Axios instance
const instance = axios.create();

// Add a request interceptor
instance.interceptors.request.use(config => {
    // Attach a timestamp indicating when the request was made
    config.metadata = { startTime: new Date() };
    return config;
}, error => {
    // Do something with request error
    return Promise.reject(error);
});

// Add a response interceptor
instance.interceptors.response.use(response => {
    // Compute and log the duration of the request
    const duration = new Date() - response.config.metadata.startTime;
    console.log(`Request to ${response.config.url} took ${duration}ms`);
    return response;
}, error => {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
});

// Usage example
instance.get('/your-endpoint').then(response => {
    // Handle response
}).catch(error => {
    // Handle error
});
This code snippet sets up Axios' interceptors to measure network request timing. A request interceptor is added to record the start time, and a response interceptor computes and logs the duration once the response is received. The interceptors also handle request and response errors, passing them through the promise chain. An example request is also shown to demonstrate its usage.