Skip to content
jshacks.dev
APIs

Implement filtering and sorting from query parameters

Implement filtering and sorting from query parameters with an allowlist of fields, so a client cannot sort or filter on columns you did not expose.

1 min read
Summarize in AI

List endpoints usually accept status=open for filtering and sort=-priority for ordering. The server should accept only fields it has chosen to expose.

filter-sort.jsJavaScript
const items = [
  { title: 'A', status: 'open', priority: 1 },
  { title: 'B', status: 'closed', priority: 3 },
  { title: 'C', status: 'open', priority: 2 },
];

const FILTERABLE = ['status'];
const SORTABLE = ['priority', 'title'];

function query(rows, params) {
  let result = rows;
  for (const field of FILTERABLE) {
    if (params.has(field)) result = result.filter((r) => r[field] === params.get(field));
  }
  const sort = params.get('sort');
  if (sort) {
    const desc = sort.startsWith('-');
    const field = desc ? sort.slice(1) : sort;
    if (!SORTABLE.includes(field)) throw new Error(`Cannot sort by ${field}`);
    result = [...result].sort((a, b) => (a[field] > b[field] ? 1 : -1) * (desc ? -1 : 1));
  }
  return result;
}

console.log(query(items, new URLSearchParams('status=open&sort=-priority')).map((r) => r.title));
Text
[ 'C', 'A' ]

The leading minus for descending order is a common convention, borrowed from JSON:API. Only the open items remain, and they are ordered by priority from high to low.

The allowlists are the security feature. If the field name from the request went straight into an SQL ORDER BY, a client could sort on a private column or inject SQL; with an allowlist, anything else is an error you can turn into a 400. For a database, map each allowed name to a column and use parameters for values.

Taggednode
Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read
APIs

Accept multipart upload in Node.js

Accept a multipart file upload in Node.js by wrapping the incoming request in a Request object and reading it with formData.

1 min read
Performance

Reduce JSON size by removing nulls

Drop null and undefined fields from an API payload with a JSON.stringify replacer, shrinking responses, and check clients treat a missing key like null.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.