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.
Previous
What is the dotenv package and how is it used in Express?
Next
What is express-session and how does session-based auth work?
More Express.js Questions
View all →- Intermediate How do you implement JWT authentication in Express.js?
- Intermediate What is Express middleware chaining and how does it work?
- Intermediate What is the helmet package and why should you use it?
- Intermediate How do you implement rate limiting in Express.js?
- Intermediate What is input validation and how do you do it in Express?