Streamlining URL Query Parameters: Customizing Axios for Clean Search Filters

On the Inmotech Frontend project, we recently tackled a common challenge in API communication: inconsistent URL query parameter serialization. This often arises when integrating with backend services that expect a specific format for array parameters, differing from the default behavior of popular HTTP clients like Axios.

Ever found yourself debugging an API request only to realize the backend isn't receiving your array parameters correctly? You send items[]=apple&items[]=orange, but the API expects items=apple&items=orange. This seemingly small difference can lead to hours of frustration.

The Challenge

Standard HTTP clients often serialize array parameters with brackets (e.g., ?filters[]=active&filters[]=new). While this is valid and widely supported, many backend frameworks, particularly those built on older conventions or custom parsers, prefer a 'flat' array format (e.g., ?filters=active&filters=new). Our goal was to ensure seamless communication without backend modifications.

The Solution: Custom paramsSerializer in Axios

Axios, a popular Promise-based HTTP client, offers a powerful paramsSerializer option. This allows us to define precisely how query parameters are converted into a URL string. We implemented a custom serializer to handle arrays without brackets.

import qs from 'qs'; // A robust query string parsing/stringifying library

// Custom paramsSerializer for Axios
const customParamsSerializer = (params) => {
  return qs.stringify(params, {
    arrayFormat: 'repeat', // Ensures `key=value1&key=value2`
    allowDots: true,      // Useful for nested objects
  });
};

// Example Axios instance configuration
const apiClient = axios.create({
  baseURL: 'https://api.example.com',
  paramsSerializer: customParamsSerializer,
});

By integrating qs (a library for query string parsing and stringifying) and configuring arrayFormat: 'repeat', we ensured that arrays like ['value1', 'value2'] are serialized as key=value1&key=value2, meeting the backend's expectations.

Building Robust Search Parameter Utilities

Beyond just array formatting, we developed a buildSearchParams utility to centralize the creation of complex query parameters. This function now intelligently handles specific filters, such as geographical data (distrito, barrio) and categorical mappings (TIPO_GRUPO_MAP), ensuring consistency across our application.

const TIPO_GRUPO_MAP = {
  'apartamento': 'APT',
  'casa': 'HS',
  // ... other mappings
};

const buildSearchParams = (filters) => {
  const searchParams = {};

  if (filters.searchQuery) {
    searchParams.q = filters.searchQuery;
  }
  if (filters.propertyType) {
    searchParams.type = TIPO_GRUPO_MAP[filters.propertyType] || filters.propertyType;
  }
  if (filters.district) {
    searchParams.distrito = filters.district;
  }
  if (filters.neighborhood) {
    searchParams.barrio = filters.neighborhood;
  }
  // Add more complex filter logic here,
  // potentially handling arrays directly if needed.

  return searchParams;
};

// Usage with apiClient
const filters = {
  searchQuery: 'modern home',
  propertyType: 'casa',
  district: 'centro',
};
apiClient.get('/properties', { params: buildSearchParams(filters) });
// This will now correctly serialize with our customParamsSerializer

This utility function acts as a single source of truth for constructing API-specific search queries, mapping frontend concepts to backend expectations and preparing them for the custom paramsSerializer.

The Lesson

Controlling how your HTTP client serializes parameters is crucial for robust API integrations. A custom paramsSerializer, especially when combined with a dedicated utility to build search parameters, eliminates common pitfalls with array formatting and ensures your frontend speaks the exact language your backend expects. This approach significantly reduces debugging time and improves the reliability of your application's data fetching.


Generated with Gitvlg.com

Streamlining URL Query Parameters: Customizing Axios for Clean Search Filters
JAIME ANDRÉS MONSERRATE VILLA

JAIME ANDRÉS MONSERRATE VILLA

Author

Share: