Sorting with Pagination
What you'll learn: How adding sort parameters to paginated API requests changes which records appear on each page and how to handle sorting correctly.
The Core Idea
When you combine sorting with pagination, the sort order determines what ends up on each page. Imagine a deck of cards: if you first sort them by suit, then deal them into piles of 10, you'll get different piles than if you sorted by rank first. The same principle applies to API responses.
Sorting must be consistent and applied before pagination on the server. If you request "page 2 of users sorted by creation date," the API should sort all users by creation date, then return records 11-20 (assuming 10 per page).
Common Sort Query Parameters
APIs typically use query strings like:
GET /api/products?sort=price&order=asc&page=1&limit=20
Or a combined format:
GET /api/products?sort=-price&page=1&limit=20
(The minus sign indicates descending order)
Why Sort Order Matters for Pagination
If sorting changes between page requests, you might see duplicate records or missing records. For example, if new items are added while you're browsing sorted results, page boundaries shift. This is why cursor-based pagination often works better with frequently-changing sorted data.
Handling in Fetch Requests
const params = new URLSearchParams({
page: 2,
limit: 10,
sort: 'createdAt',
order: 'desc'
});
fetch(`/api/users?${params}`)
.then(res => res.json())
.then(data => {
// Sorted and paginated results
});
Key Takeaway: Sorting must happen before pagination on the server, and consistent sort parameters across requests prevent duplicate or missing records when navigating pages.