Facebook Pixel

Why use cursor pagination instead of offset for infinite scroll?

Cursor is fast (MongoDB uses the index, no scanning of skipped docs) and stable (new items inserted between requests do not cause duplicates or skips). Offset is slow for large pages and unstable when items are inserted.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in How to Implement Infinite Scroll in Node.js

Use cursor pagination. Fetch limit + 1 items. If you get limit + 1, there is more; pop the extra. Return nextCursor and hasMore. The frontend keeps calling with the last cursor until hasMore is false. Index the cursor field.

To know if there is more without a separate count query. If you get limit + 1 items, there is more (pop the extra). If you get limit or fewer, there is no more. Avoids the countDocuments query.

An index on the cursor field. For a feed sorted by createdAt descending, use schema.index({ createdAt: -1 }). Without an index, the cursor query is not faster than offset.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.