Dynamic URL Modification with Axios Interceptors

This article explains how to intercept and dynamically modify request URLs in the Axios HTTP client using request interceptors. By utilizing Axios interceptors, developers can inspect, rewrite, or augment paths, base URLs, and query parameters globally or on specific instances before a request is sent. This pattern centralizes logic for routing, environment handling, multi-tenancy, and parameter injection across an entire application.

Understanding Axios Request Interceptors

The primary mechanism for intercepting and modifying request URLs in Axios is the request interceptor API (axios.interceptors.request.use()). Interceptors act as middleware layers that receive the Axios configuration object (AxiosRequestConfig) before the HTTP request is dispatched across the network.

When an interceptor runs, it allows direct mutation or replacement of the config object. The modified configuration must be returned so Axios can proceed with the request.

Implementation

To modify a URL dynamically, register an interceptor on the global axios object or on a custom instance created with axios.create().

import axios from 'axios';

// Create an Axios instance
const apiClient = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 5000,
});

// Register the request interceptor
apiClient.interceptors.request.use(
  (config) => {
    // Dynamic value, such as a localized route or tenant identifier
    const currentLocale = getLocale(); // e.g., 'en-US'

    // 1. Modifying the URL path directly
    if (config.url && !config.url.startsWith('http')) {
      config.url = `/${currentLocale}${config.url}`;
    }

    // 2. Modifying the baseURL dynamically based on specific endpoints
    if (config.url && config.url.includes('/auth/')) {
      config.baseURL = 'https://auth.example.com';
    }

    // 3. Dynamically appending query parameters to the URL
    config.params = {
      ...config.params,
      requestId: crypto.randomUUID(),
    };

    return config;
  },
  (error) => {
    // Handle request setup errors
    return Promise.reject(error);
  }
);

Key Configuration Properties for URL Manipulation

Axios provides several properties within the config object to manage URL construction:

Removing an Interceptor

If an interceptor is only needed temporarily (such as during a specific user session or testing context), it can be removed using eject():

const myInterceptor = apiClient.interceptors.request.use((config) => {
  // Logic to modify URL
  return config;
});

// Eject the interceptor when no longer needed
apiClient.interceptors.request.eject(myInterceptor);