Why cap the limit in pagination?
To prevent abuse. Without a cap, a client can request 10000 items, eating memory and bandwidth. Use Math.min(parseInt(req.query.limit) || 20, 100). Most UIs only show 20 at a time anyway.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Pagination Best Practices for Node.js APIs
Always paginate, cap the limit, use cursor for large collections, use offset for page numbers, index the sort or cursor field, use .lean() and .select(), return metadata, use a stable sort (tiebreaker on _id), handle empty results, validate the cursor, use query params not body, and document the scheme.
If you sort by createdAt, ties are possible (two items with the same timestamp). Without a tiebreaker, cursor pagination can skip or duplicate items. Use .sort({ createdAt: -1, _id: 1 }) to make the sort stable.
So the client does not have to handle null. Return { data: [], total: 0 } for offset or { data: [], nextCursor: null, hasMore: false } for cursor. Consistent shapes make the client simpler.
Still have questions?
Browse all our FAQs or reach out to our support team
