🚀 Express.js Intermediate

How do you implement pagination in an Express REST API?

Answer

Pagination limits the amount of data returned per request. The two main approaches: Offset/Page pagination: client sends ?page=2&limit=20. Server calculates skip: const skip = (page - 1) * limit; const items = await Model.find().skip(skip).limit(limit);. Return total count and page metadata. Simple to implement but inefficient for large offsets (database must scan skipped rows). Cursor pagination: client sends a cursor (last item's ID): ?after=lastId. Server queries: Model.find({ _id: { $gt: lastId } }).limit(20). More efficient for large datasets and consistent under concurrent writes. Return a nextCursor in the response. Cursor pagination is preferred for infinite-scroll UIs.