How to properly URL encode multiple sorting parameters for Airtable API requests

I’m working with the Airtable API and need help with URL encoding for sorting multiple fields with different directions.

I have a sorting configuration like this:

const sortConfig = [
  { name: "productName", order: "asc" },
  { name: "price", order: "desc" },
  { name: "brand", order: "asc" }
];

I’m trying to build the query string but my current approach isn’t working correctly:

let queryString;

sortConfig.forEach(item => {
  console.log(item.name, item.order);
  queryString += `&sort%5B0%5D%5Bname%5D=${encodeURIComponent(
    item.name
  )}&sort%5B0%5D%5Border%5D=${item.order}`;
});

queryString;

What’s the correct way to encode multiple sort fields with their respective directions for the Airtable API? I think I’m missing something with the array indexing in the URL parameters.

You’re using index [0] for all sort parameters instead of incrementing it for each field.

Here’s how I build Airtable sort queries:

const sortConfig = [
  { name: "productName", order: "asc" },
  { name: "price", order: "desc" },
  { name: "brand", order: "asc" }
];

let queryString = "";

sortConfig.forEach((item, index) => {
  queryString += `&sort%5B${index}%5D%5Bfield%5D=${encodeURIComponent(item.name)}&sort%5B${index}%5D%5Bdirection%5D=${item.order}`;
});

Two fixes:

  1. Use index from forEach instead of hardcoded [0]
  2. Airtable wants field and direction as parameter names, not name and order

I hit this exact problem last year pulling product data from our Airtable base. Wasted way too much time debugging before realizing the parameter names were wrong.

Final URL should look like:
sort[0][field]=productName&sort[0][direction]=asc&sort[1][field]=price&sort[1][direction]=desc

You can also use URLSearchParams to clean it up:

const params = new URLSearchParams();
sortConfig.forEach((item, index) => {
  params.append(`sort[${index}][field]`, item.name);
  params.append(`sort[${index}][direction]`, item.order);
});