Course contentsShow
← Web Development
Lesson 1509 of 2,98227. REST API Design for FrontendFree lesson

Cursor-Based Pagination

Using cursors or tokens to navigate through result sets without skipping or duplicating items.

Cursor-Based Pagination

You'll learn how to use cursor tokens to navigate paginated data without skipping or duplicating results.

What Is Cursor-Based Pagination?

Cursor-based pagination uses an opaque token (the "cursor") that points to a specific position in your dataset. Instead of asking for "page 3" or "skip 40 items," you ask for "the next 20 items after this cursor." The server remembers where you left off and gives you the next batch plus a new cursor for the subsequent request.

Think of it like a bookmark in a book that's constantly being updated with new pages. Your bookmark (cursor) always knows exactly where you stopped reading, even if someone adds pages earlier in the book.

Why Use Cursors Instead of Offsets?

With offset-based pagination (lesson 1508), if items are added or removed while you're paginating, you might see duplicates or skip entries. Cursor-based pagination solves this by anchoring to a specific item's identifier or timestamp, not a numeric position.

The cursor is typically encoded (base64, for example) and contains information like the last item's ID or creation timestamp. The client doesn't need to understand it—just store it and send it back.

How It Works

  1. First request: GET /api/posts?limit=20 returns 20 posts plus a next_cursor token
  2. Second request: GET /api/posts?limit=20&cursor=abc123xyz returns the next 20 posts after that cursor
  3. Continue: Repeat until no next_cursor is returned (end of data)

The API response might include both next_cursor (for forward pagination) and optionally prev_cursor (for backward navigation).

Key Takeaway: Cursor-based pagination uses opaque tokens to maintain consistent position in result sets, preventing duplicates or skipped items even when the underlying data changes.