REST API Masterclass
Architecting Modern Backends01.Home02.What is REST?03.HTTP Deep Dive04.URI Best Practices05.JSON & Data Formats06.Environment Setup07.Your First Resource08.Advanced Controllers09.Database Strategy10.JWT Authentication11.Role-Based Auth (RBAC)12.API Versioning13.Filtering & Searching14.Pagination & Sorting15.Global Error Handling16.Rate Limiting17.CORS & Security18.Swagger & OpenAPI19.Testing with Supertest20.Webhooks & Caching21.Production Checklist
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=202. 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,price4. 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.