Dynamic Endpoints with Path Variables in Axios

Constructing dynamic endpoints in Axios involves injecting variable data—such as resource IDs, slugs, or user identifiers—directly into the URL path. This guide explains how to achieve path variable interpolation in Axios using JavaScript template literals, URL encoding for safety, reusable utility functions, and request interceptors for automated path parameter replacement.

1. Using ES6 Template Literals

The most straightforward and native way to interpolate variables into an Axios request path is by using JavaScript ES6 template literals (backticks).

import axios from 'axios';

const userId = 123;
const postId = 456;

// Dynamic URL path using template literals
axios.get(`https://api.example.com/users/${userId}/posts/${postId}`)
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request failed:', error);
  });

When using a configured Axios instance with a baseURL, concatenate the dynamic path accordingly:

const apiClient = axios.create({
  baseURL: 'https://api.example.com/api/v1'
});

const resource = 'orders';
const orderId = 'ord_98765';

apiClient.get(`/${resource}/${orderId}`)
  .then(response => console.log(response.data));

2. Encoding Dynamic Path Variables

Path variables may contain special characters (such as spaces, slashes, or query symbols) that can break the URL structure. Always wrap user-supplied variables with encodeURIComponent to ensure valid URL formatting.

const username = 'john doe/admin';
const encodedUsername = encodeURIComponent(username);

axios.get(`https://api.example.com/profiles/${encodedUsername}`);
// Sends request to: https://api.example.com/profiles/john%20doe%2Fadmin

3. Creating a Reusable URL Builder Helper

If your application defines API routes as static template strings (e.g., /users/:userId/posts/:postId), you can use a helper function to replace placeholders dynamically.

function compilePath(template, params) {
  return template.replace(/:([a-zA-Z0-9_]+)/g, (match, key) => {
    if (params[key] === undefined) {
      throw new Error(`Missing path parameter: ${key}`);
    }
    return encodeURIComponent(params[key]);
  });
}

// Example usage:
const endpoint = compilePath('/users/:userId/posts/:postId', {
  userId: 42,
  postId: 108
});

axios.get(`https://api.example.com${endpoint}`);
// Sends request to: https://api.example.com/users/42/posts/108

4. Automating Path Interpolation with Axios Interceptors

You can extend Axios globally so that it parses dynamic path variables declared in the request configuration. This keeps dynamic URL management declarative.

import axios from 'axios';

const api = axios.create({
  baseURL: 'https://api.example.com'
});

// Request interceptor to replace path parameters
api.interceptors.request.use((config) => {
  if (config.pathParams && config.url) {
    config.url = config.url.replace(/:([a-zA-Z0-9_]+)/g, (match, key) => {
      return config.pathParams[key] !== undefined
        ? encodeURIComponent(config.pathParams[key])
        : match;
    });
  }
  return config;
});

// Usage
api.get('/organizations/:orgId/members/:memberId', {
  pathParams: {
    orgId: 'acme-corp',
    memberId: 55
  }
});
// Sends request to: https://api.example.com/organizations/acme-corp/members/55

Summary of Best Practices