TExcelTAD
Home › Express & NestJS › Pagination, Filtering & Sorting

Pagination, Filtering & Sorting

A GET /products that returns 50,000 rows is slow for the server, slow over the network and useless for a client that shows 20 items at a time. Real list endpoints let clients filter, sort and paginate through query parameters.

A typical query interface

text
GET /products?category=books&minPrice=10&sort=-price&page=2&limit=5
Parameter Meaning Default
category, minPrice, … filters — only matching items none
q free-text search none
sort field to sort by; a - prefix means descending e.g. id
page, limit which slice to return 1, 20

Always cap limit (e.g. at 100) so nobody can request everything at once.

The pipeline: filter → sort → paginate

Order matters. You filter first (fewer items to sort), sort the remainder, then cut out the page. The total count is taken after filtering, before paginating:

ts · try it yourself
type Product = { id: number; name: string; category: string; price: number };

const products: Product[] = [
  { id: 1, name: 'Desk', category: 'furniture', price: 120 },
  { id: 2, name: 'Novel', category: 'books', price: 15 },
  { id: 3, name: 'Lamp', category: 'furniture', price: 35 },
  { id: 4, name: 'Atlas', category: 'books', price: 40 },
  { id: 5, name: 'Cookbook', category: 'books', price: 25 },
  { id: 6, name: 'Chair', category: 'furniture', price: 60 },
];

function listProducts(opts: { category?: string; sort?: string; page: number; limit: number }) {
  let rows = products.filter((p) => !opts.category || p.category === opts.category);

  if (opts.sort) {
    const desc = opts.sort.startsWith('-');
    const key = (desc ? opts.sort.slice(1) : opts.sort) as keyof Product;
    rows = [...rows].sort((a, b) => (a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0) * (desc ? -1 : 1));
  }

  const total = rows.length;
  const start = (opts.page - 1) * opts.limit;
  return {
    data: rows.slice(start, start + opts.limit).map((p) => `${p.name} (${p.price})`),
    meta: { page: opts.page, limit: opts.limit, total, pages: Math.ceil(total / opts.limit) },
  };
}

console.log(listProducts({ category: 'books', sort: '-price', page: 1, limit: 2 }));
console.log(listProducts({ category: 'books', sort: '-price', page: 2, limit: 2 }));
{
  data: [ 'Atlas (40)', 'Cookbook (25)' ],
  meta: { page: 1, limit: 2, total: 3, pages: 2 }
}
{
  data: [ 'Novel (15)' ],
  meta: { page: 2, limit: 2, total: 3, pages: 2 }
}

The Express endpoint

The route parses and validates the query, then runs the same pipeline. Sorting is limited to an allow-list of fields — never sort by an arbitrary client-provided key (with a database, that could even become an injection risk):

node · try it yourself
const express = require('express');

const products = [
  { id: 1, name: 'Desk', category: 'furniture', price: 120 },
  { id: 2, name: 'Novel', category: 'books', price: 15 },
  { id: 3, name: 'Lamp', category: 'furniture', price: 35 },
  { id: 4, name: 'Atlas', category: 'books', price: 40 },
  { id: 5, name: 'Cookbook', category: 'books', price: 25 },
  { id: 6, name: 'Chair', category: 'furniture', price: 60 },
];
const SORTABLE = ['id', 'name', 'price'];

const app = express();

app.get('/products', (req, res) => {
  const page = Math.max(1, Number.parseInt(req.query.page, 10) || 1);
  const limit = Math.min(100, Math.max(1, Number.parseInt(req.query.limit, 10) || 20));
  const sort = typeof req.query.sort === 'string' ? req.query.sort : 'id';
  const field = sort.replace(/^-/, '');
  if (!SORTABLE.includes(field)) {
    return res.status(400).json({ error: `sort must be one of ${SORTABLE.join(', ')}` });
  }
  const dir = sort.startsWith('-') ? -1 : 1;

  let rows = products;
  if (req.query.category) rows = rows.filter((p) => p.category === req.query.category);
  if (req.query.minPrice) rows = rows.filter((p) => p.price >= Number(req.query.minPrice));
  if (req.query.q) rows = rows.filter((p) => p.name.toLowerCase().includes(String(req.query.q).toLowerCase()));

  rows = [...rows].sort((a, b) => (a[field] < b[field] ? -1 : a[field] > b[field] ? 1 : 0) * dir);
  const total = rows.length;
  const data = rows.slice((page - 1) * limit, page * limit).map((p) => p.name);
  res.json({ data, meta: { page, limit, total } });
});

const server = app.listen(0, async () => {
  const base = `http://localhost:${server.address().port}/products`;
  const queries = [
    '?limit=4',
    '?limit=4&page=2',
    '?category=furniture&sort=-price',
    '?minPrice=30&sort=name',
    '?q=OOK',
    '?sort=secret',
  ];
  for (const qs of queries) {
    const res = await fetch(base + qs);
    console.log(qs.padEnd(32), res.status, await res.text());
  }
  server.close();
});
?limit=4                         200 {"data":["Desk","Novel","Lamp","Atlas"],"meta":{"page":1,"limit":4,"total":6}}
?limit=4&page=2                  200 {"data":["Cookbook","Chair"],"meta":{"page":2,"limit":4,"total":6}}
?category=furniture&sort=-price  200 {"data":["Desk","Chair","Lamp"],"meta":{"page":1,"limit":20,"total":3}}
?minPrice=30&sort=name           200 {"data":["Atlas","Chair","Desk","Lamp"],"meta":{"page":1,"limit":20,"total":4}}
?q=OOK                           200 {"data":["Cookbook"],"meta":{"page":1,"limit":20,"total":1}}
?sort=secret                     400 {"error":"sort must be one of id, name, price"}

Offset vs cursor pagination

page/limit (also called offset pagination) is easy, but has two weaknesses on large, changing datasets: the database still scans all skipped rows, and items shift between pages when new rows are inserted. Cursor pagination returns an opaque pointer to "the item after the last one you saw":

text
GET /events?limit=20                    → { data: [...], nextCursor: "ev_1040" }
GET /events?limit=20&after=ev_1040      → { data: [...], nextCursor: "ev_1060" }
Offset (page) Cursor (after)
Jump to page 7 yes no
Stable under inserts no yes
Fast on huge tables gets slower constant
Good for admin tables, search results feeds, logs, infinite scroll
ts · try it yourself
const events = Array.from({ length: 7 }, (_, i) => ({ id: 101 + i }));

function page(after: number | undefined, limit: number) {
  const rows = events.filter((e) => after === undefined || e.id > after).slice(0, limit);
  const last = rows.at(-1);
  const hasMore = last !== undefined && events.some((e) => e.id > last.id);
  return { ids: rows.map((e) => e.id), nextCursor: hasMore ? last.id : null };
}

let cursor: number | undefined;
do {
  const result = page(cursor, 3);
  console.log(result);
  cursor = result.nextCursor ?? undefined;
} while (cursor !== undefined);
{ ids: [ 101, 102, 103 ], nextCursor: 103 }
{ ids: [ 104, 105, 106 ], nextCursor: 106 }
{ ids: [ 107 ], nextCursor: null }

Tip: Some APIs also send pagination links in a Link header (<…?page=3>; rel="next"), the way GitHub's API does. Including meta.total in the body is simpler for most frontends.

Test yourself

In which order should a list endpoint process the data?

  1. paginate → sort → filter
  2. sort → paginate → filter
  3. filter → sort → paginate
  4. Order doesn't matter

Why limit sort to an allow-list of fields?

  1. To make sorting faster
  2. To stop clients sorting by hidden or arbitrary fields, which can leak data or enable injection
  3. Express requires it
  4. Because only numbers can be sorted

What is the main advantage of cursor pagination over page numbers?

  1. You can jump to any page
  2. Results stay stable when new items are inserted
  3. It needs no database
  4. It always returns everything