Pagination & Sorting

Returning large amounts of data at once is one of the quickest ways to crash both your server and the client browser. You must implement pagination.

1. Offset Pagination

The standard approach using page and limit (or offset and count).

GET /posts?page=2&limit=20

2. Cursor Pagination (Recommended)

Instead of pages, you pass a "cursor" (usually an ID or timestamp) of the last item received. This is much more stable for "Infinite Scroll" UIs where data is constantly being added.

GET /activity?after=655a12b8e...

3. Sorting

Allow clients to order data by one or more fields. Use a comma-separated list or a minus sign for descending order.

# Sort by price (ascending)
      GET /products?sort=price

      # Sort by rating (desc) then price (asc)
      GET /products?sort=-rating,price

4. Pagination Metadata

Always tell the client where they are in the dataset.

{
        "total": 150,
        "limit": 10,
        "page": 3,
        "pages": 15,
        "data": [...]
      }
Performance Tip: Never allow an unlimited limit. Set a Hard Maximum (e.g., 100 items per request) in your backend to prevent malicious or accidental resource exhaustion.