Pagination — API

Pagination splits a long list into pages, so each response stays light (performance). Offset pagination: the client sends ?page=2&limit=5 (the page number and…

Scroll a marketplace's product list to the bottom. A loading icon shows for a moment, then more products appear. The app never asks for every product at once, only for a few first, then again when you reach the bottom.

That's called pagination: a long list split into small pages, with the client asking for one page per request. The Bookshop printed catalogue works like that too. Nobody prints 20,000 books on one sheet. The catalogue is split into pages, and the bottom of each page gives its number, for example "page 2 of 4". In the API, one page of the catalogue is one response: GET /books doesn't send every book at once, but 5 books first, then the next 5 when asked.

Why split it into pages

The Bookshop catalogue now holds 20 books. Later it could be 20,000. If all of them are sent in one response, the response is big, the server works hard, and the buyer's phone is slow to show it. But only the top 5 get looked at. Pagination protects performance (speed): each request carries only one page.

page and limit in the query string

The client picks its page through the query string, as in the URLs & Endpoints lesson:

GET /books?page=2&limit=5

This endpoint reads those two numbers:

app.get("/books", (req, res) => {
  const page = parseInt(req.query.page) || 1;
  const limit = parseInt(req.query.limit) || 5;
  const start = (page - 1) * limit;
  const data = books.slice(start, start + limit);
  const total = books.length;
  const totalPages = Math.ceil(total / limit);

  res.json({
    data,
    meta: { page, limit, total, totalPages },
    links: {
      first: `/books?page=1&limit=${limit}`,
      prev: page > 1 ? `/books?page=${page - 1}&limit=${limit}` : null,
      next: page < totalPages ? `/books?page=${page + 1}&limit=${limit}` : null,
      last: `/books?page=${totalPages}&limit=${limit}`,
    },
  });
});

With 20 books and a limit of 5, you get this:

page start slice Books
1 0 slice(0, 5) 1 to 5
2 5 slice(5, 10) 6 to 10
4 15 slice(15, 20) 16 to 20
5 20 slice(20, 25) none: data is empty, still 200

The number of pages: 20 books divided by 5 = 4 pages. With 25 in total and 10 per page, that's 2.5, rounded up to 3 pages, and the last page holds 5.

meta and links

This is the response for page 2, laid out neatly:

{
  "data": [
    { "id": 6, "title": "Edensor" },
    { "id": 7, "title": "Child of All Nations" },
    { "id": 8, "title": "Man Tiger" },
    { "id": 9, "title": "The Land of Five Towers" },
    { "id": 10, "title": "Paper Boat" }
  ],
  "meta": { "page": 2, "limit": 5, "total": 20, "totalPages": 4 },
  "links": {
    "first": "/books?page=1&limit=5",
    "prev": "/books?page=1&limit=5",
    "next": "/books?page=3&limit=5",
    "last": "/books?page=4&limit=5"
  }
}

In Laravel, the single line Book::paginate(5) reads ?page= by itself. It returns the data plus the same information (current_page, per_page, total, last_page, next_page_url and more).

Offset vs cursor

The way above is called offset pagination. Offset means the distance from the start of the list: "skip this many books, then take this many". Its problem appears when the data changes between two requests.

Say you open page 1: books 1 to 5. Then book number 3 is deleted, and every book after it moves forward one position. Positions 5 to 9 now hold books 7 to 11, so page 2 starts with book 7. Book 6 moved to page 1, which you already opened, so you never see book 6. The opposite happens too. In a "newest first" list, a new book arrives at the front and moves every book back one position. So the last book of page 1 appears twice, again at the start of page 2.

Cursor pagination doesn't count positions. The client sends the id of the last book it saw, and the server takes the books after that id. That id is called the cursor (a marker). For "5 books after number 5", the code is:

const after = parseInt(req.query.after) || 0;
const rest = books.filter((b) => b.id > after);
const data = rest.slice(0, limit);
const nextCursor = rest.length > limit ? data[data.length - 1].id : null;

filter keeps the books whose id is bigger than after, and nextCursor is the cursor for the next request (null when there are no more books). GET /books?limit=5&after=5 still starts with book 6, even though book 3 was deleted. Nothing is skipped, nothing appears twice.

Offset (?page=2) Cursor (?after=5)
Jump to page 7 yes no, it goes in order
"Page 2 of 4" yes usually no total
Data changes along the way rows can be skipped or doubled stable
A far page, for example page 5,000 in a database gets slower: the database still reads every row that OFFSET skips, then throws it away stays fast: WHERE id > ? starts right at its place through the index
Good for admin tables, numbered search results feeds, infinite scroll, chat history

OFFSET and WHERE id > ? in this table are SQL commands. SQL is the language for asking a database for data, and it is covered in the lesson Querying the Database from an API. An index is a sorted list the database builds so it can find rows fast, like the index at the back of a book.

In Laravel, cursor pagination is Book::cursorPaginate(5). Its cursor looks like random text. In fact it holds the last row's values, for example {"id":5,...}, encoded with base64 (a way of writing data with plain letters and digits). It is not a secret: anyone can read and change it. The idea is the same as ?after=5.

⚠️ Page numbers that make the maths wrong

TL;DR: Pagination splits a long list into pages, so each response stays light (performance). Offset pagination: the client sends ?page=2&limit=5 (the page number and the number of books per page). The server calculates parseInt(req.query.page) || 1, start = (page - 1) * limit, books.slice(start, start + limit), and totalPages = Math.ceil(total / limit) (25 items at 10 per page = 3 pages). The response is { data, meta: { page, limit, total, totalPages }, links: { first, prev, next, last } }: meta holds facts about the page, and links holds the addresses of other pages. An empty page is still 200. In Laravel: Book::paginate(5). Offset can skip or double items when the data changes between two requests. A cursor (?after=5, or cursorPaginate in Laravel) continues from the last item seen, so it's stable, but it can't jump to a given page.

⚡ Why split it into pages

Meaning: Pagination means splitting a long list into pages, with the client asking for one page per request. Sending every book at once makes the response big, the server busy and the buyer's phone slow to show it. But only the top 5 get looked at. Pagination protects performance: each request carries only one page.

⚡ page and limit

Write:

const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 5;
const start = (page - 1) * limit;
const data = books.slice(start, start + limit);
const total = books.length;
const totalPages = Math.ceil(total / limit);
Guess first: 25 items in total, 10 per page. Math.ceil rounds up. How many pages?

Three pages. 25 divided by 10 is 2.5, and Math.ceil rounds it up to 3. The last page holds 5 items.

Meaning: The client sends ?page=2&limit=5: page is the page number (starting at 1), and limit is the number of books per page. req.query.page is text, so parseInt turns it into a number, and || 1 gives the default. Page 1 starts at position 0 in the array, so start = (page - 1) * limit. slice takes the books from start up to just before start + limit.

⚡ Offset can skip, a cursor stays in place

Meaning: Offset pagination counts positions: "skip this many books, take this many". You open page 1 (books 1 to 5), then book number 3 is deleted, and every book after it moves forward one position. Page 2 now starts with book 7, and book 6 moved to page 1, so you never see it. Cursor pagination sends the id of the last book you saw: ?after=5 means "after book number 5". So the next page still starts with book 6.

What you will learn