Dynamic Axios Query Strings with URLSearchParams
Constructing dynamic query strings in Axios is essential for handling
API requests with variable search filters, sorting options, and
pagination. By integrating the native JavaScript
URLSearchParams API with Axios, developers can
programmatically build, encode, and append query parameters without
manual string concatenation. This guide demonstrates how to build
dynamic query parameters cleanly and securely using
URLSearchParams in your Axios HTTP requests.
Why Use
URLSearchParams with Axios?
While Axios accepts plain JavaScript objects in the
params configuration, using URLSearchParams
offers distinct advantages:
- Automatic Encoding: Properly encodes special characters and whitespace according to URL standards.
- Duplicate Keys: Allows multiple values for the
exact same key (e.g.,
?category=tech&category=news) using the.append()method. - Dynamic Mutation: Easily add, remove, or conditionally append query parameters before executing the request.
Constructing Dynamic Parameters
To build a query string dynamically, instantiate
URLSearchParams and use its built-in methods like
.append() or .set() based on your application
state or incoming filter objects.
import axios from 'axios';
// Example dynamic filter object
const filters = {
search: 'javascript frameworks',
page: 2,
limit: 10,
tags: ['frontend', 'react', 'vue'],
inStockOnly: true,
discountCode: null // Should be excluded dynamically
};
// Initialize URLSearchParams
const params = new URLSearchParams();
// Loop through filters and dynamically append valid values
Object.entries(filters).forEach(([key, value]) => {
if (value !== null && value !== undefined && value !== '') {
if (Array.isArray(value)) {
// Append each array element for repeated keys
value.forEach(item => params.append(key, item));
} else {
params.append(key, String(value));
}
}
});Passing
URLSearchParams to Axios
Axios natively accepts a URLSearchParams instance in the
params configuration property.
async function fetchData() {
try {
const response = await axios.get('https://api.example.com/items', {
params: params
});
console.log(response.data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
fetchData();The resulting request URL will be properly formatted and encoded:
https://api.example.com/items?search=javascript+frameworks&page=2&limit=10&tags=frontend&tags=react&tags=vue&inStockOnly=true
Using
URLSearchParams as a Custom Serializer
Alternatively, you can use URLSearchParams inside the
paramsSerializer option. This approach allows you to keep
passing regular JavaScript objects directly to params while
delegating the serialization logic to URLSearchParams.
import axios from 'axios';
const apiClient = axios.create({
baseURL: 'https://api.example.com',
paramsSerializer: (params) => {
const searchParams = new URLSearchParams();
Object.entries(params).forEach(([key, value]) => {
if (Array.isArray(value)) {
value.forEach(v => searchParams.append(key, v));
} else if (value !== undefined && value !== null) {
searchParams.append(key, value);
}
});
return searchParams.toString();
}
});
// Clean usage without manually building URLSearchParams each time
apiClient.get('/products', {
params: {
sort: 'price_asc',
brand: ['apple', 'samsung']
}
});This configuration ensures consistent query string generation across all requests made by the Axios instance.