16 min read
API pagination: cursor vs offset, and filtering
In one sentence: Paginating is returning a long list in pieces: the client asks for a page and the response tells it how to ask for the next one. With an offset (“skip the first 20”), if the list changes between two pages, an item shows up twice or gets lost; with a cursor (“the ones that come after this one”), it doesn't.
What you will learn
- Explain why an API returns its lists in pages, with a maximum limit.
- Check with real requests that, if the list changes, an offset repeats or skips items, and a cursor doesn't.
- Give the next page in the Link header (RFC 8288) and follow it with curl, on GitHub and in your API.
- Filter and sort in the query string, with each parameter validated.
Before you start, read: 02-errors.md
The problem
Section titled “The problem”Imagine the shop has 40,000 orders. The phone app shows the ten latest, and asks for GET /orders. The API from the previous lesson sends it all 40,000: about 2.4 MB of JSONJSON stands for JavaScript Object Notation.A format for writing data as text, with braces, quotes and colons: {"product":"mug","quantity":2}. People can read it, and so can almost any programming language, and it’s the most common format for the data that travels between a frontend and a backend.Go to definition, with four fields per order. The phone throws away 39,990, and the server prepared them all.
The solution is to paginate: return the list in pieces. But the most intuitive way has a catch. The delivery company from the introduction reads the paid orders every morning, 50 at a time. If a new order is paid while it reads the first page, the second one starts with an order it already had. And if one from the first page leaves the list, the second page skips another one: a parcel left undelivered.
The analogy
Section titled “The analogy”The analogy
Think of the shop’s mailbox: a stack of letters, with the new ones on top. Luis reads the five on top, notes down “I’ve done five” and goes to lunch.
While he eats, a letter arrives. When he comes back, he sets aside the five on top and carries on. But the new one is among them, so the first letter he reads is one he had already read. And if someone had taken one of the letters he’d read, he’d have skipped another without noticing.
Ana makes a different note: “the last one was the print shop’s.” When she comes back, she looks for that letter and carries on with the one below it, however many arrive on top. “I’ve done five” is an offset; “the print shop’s” is a cursor.
Where the analogy breaks down
- Ana recognizes her letter at a glance. A server needs each item to have a unique place in the order, like the id.
- With “I’ve done five,” Luis can jump to letter 40. With a cursor you can’t jump to page 8: you can only carry on from where you were.
How it really works
Section titled “How it really works”A long list is requested in pages
Section titled “A long list is requested in pages”PaginationReturning a long list in chunks, called pages, instead of all at once. The client says how many items it wants and where to start, usually in the query string, and the response tells it how to ask for the next page.Go to definition has two parts: the client says how many items it wants and from where, in the Query stringThe part of a URL that comes after “?”: data in name=value pairs separated by “&”, such as q=mug&sort=price. It travels to the server attached to the path, and it’s used to search, filter or choose a page of results.Go to definition (Phase 2), and the response tells it how to ask for the next ones.
In the shop, how many goes in ?limit=: 10 by default, and 50 at most. The maximum is set by the server, not the client: without it, ?limit=1000000 would be the whole list again. GitHub does the same with its per_page: 30 by default and 100 at most.
The offset: “skip the first 20”
Section titled “The offset: “skip the first 20””The offset counts positions. ?limit=10&offset=20 means “skip the first 20 and give me 10”: page 3. Many APIs call it offset too, or use page and per_page: the same, counted another way.
In the project, the function is in a new file:
// Skip the first "offset" and give me "limit". It's the most direct way, but if a new order comes// in between one page and the next, everything shifts one place and an order shows up twice.export function pageByOffset(list: Order[], limit: number, offset: number) { const page = list.slice(offset, offset + limit); const hasMore = list.length > offset + limit; return { page, next: hasMore ? offset + limit : undefined };}list.slice(start, end)copies the items from positionstartup toend, not included. Positions start at 0.condition ? a : bisaif the condition is true andbif it isn’t.nextis where the next page starts, orundefinedif there are no more (hasMore).
If the list changes, the offset gets it wrong
Section titled “If the list changes, the offset gets it wrong”The offset counts positions, and positions move. Orders go from newest to oldest, so a new one comes in first and pushes all the others down one place:
- Shop's API → Delivery company25, 24, 23, 22 and 21
- Shop's API → A customer in the app201, order 26
- Shop's API26 comes in first
and 21 drops to place 6 - Shop's API → Delivery company21, 20, 19, 18 and 17 (21, again)
The other way around, if an order from the first page leaves the list (it’s cancelled, and the company only asks for the pending ones), everything moves up one place. The first one of the next page moves to place 5, already read, and nobody sees it.
With an offset, what comes in ahead repeats and what leaves ahead gets skipped. And the server can’t warn anyone: it doesn’t remember who was reading what.
The cursor: “give me the ones after this one”
Section titled “The cursor: “give me the ones after this one””A Cursor (in pagination)A piece of text that marks how far you’ve read in a list split into pages, so you can ask for “the ones after this one.” The server writes it, and the client only sends it back as it is. Unlike “skip the first 20,” it doesn’t get it wrong if the list changes between one page and the next.Go to definition doesn’t count positions: it points at an item. In the shop, the cursor carries the id of the page’s last order, and the next page is the ones with a lower id:
// The list goes from newest to oldest: the ones after the cursor are the ones with a lower id.// Even if new orders come in, the cursor still points at the same place.export function pageByCursor(list: Order[], limit: number, after?: number) { const remaining = after === undefined ? list : list.filter((order) => order.id < after); const page = remaining.slice(0, limit); const hasMore = remaining.length > limit; return { page, next: hasMore ? createCursor(page.at(-1)!.id) : undefined };}after?: numberis optional: the first page has no cursor.filterkeeps only the orders with a lower id (lesson 2 of Phase 3), andslice(0, limit)takes the first ones.page.at(-1)is the last one on the page. The!tells TypeScript it won’t beundefined: ifhasMoreis true, the page isn’t empty.
Order 26 arriving doesn’t change which orders have an id lower than 21, and neither does order 24 being cancelled. The cursor keeps a value, not a position, and it works even if the order it points at is no longer in the list.
The cursor is opaque, not secret
Section titled “The cursor is opaque, not secret”The client gets a text like MjM, not the number 23:
// The cursor is the id of the page's last order, in base64url. The client doesn't have to// understand it: only send it back to ask for the next page. That way the server can change what// it carries inside without breaking anyone.export function createCursor(id: number): string { return Buffer.from(String(id)).toString('base64url');}
// If the text wasn't a cursor, the result is NaN or 0, and the schema rejects it.export function readCursor(cursor: string): number { return Number(Buffer.from(cursor, 'base64url').toString());}Buffer.from(String(id))turns the id into bytes (lesson 4 of Phase 3), andtoString('base64url')writes them with letters, numbers,-and_, which travel well in a URL.readCursorgoes back the other way. If the text wasn’t a cursor, the result isNaN(“not a number”) or0.
Base64url doesn’t encrypt anything: node -p "Buffer.from('MjM', 'base64url').toString()" writes 23. Its purpose is to make the cursor opaque: the client doesn’t interpret it, it only sends it back, and the server can change what it carries without breaking anyone. GitHub’s, decoded, start with cursor:v2:: they even carry a version.
Since it comes from outside, it’s validated (lesson 7 of Phase 3), in src/schemas.ts:
// The cursor arrives as text: it's turned into the id it carries inside, and that id is checked.const cursorSchema = z .string() .transform(readCursor) .pipe(z.number({ error: 'The cursor is not valid' }).int().positive('The cursor is not valid'));.transform(readCursor) turns the text into the id, and .pipe(…) checks that id with another schema: a whole number greater than 0. ?cursor=hello ends in a 422.
Offset or cursor: what you gain and what you lose
Section titled “Offset or cursor: what you gain and what you lose”| Offset | Cursor | |
|---|---|---|
| If the list changes between two pages | Repeats or skips items | Carries on right after the last one |
| Jumping to page 8 | Yes: offset=70 |
No: only the next one (and the previous one, if the API gives it) |
| “Page 3 of 12” | Can be calculated | There’s no page number |
| With millions of rows in a database | Slow: it reads and throws away every row it skips | Fast: it goes straight to the cursor |
You’ll see the last row in Phase 5: with offset=100000, the DatabaseA program that stores data in an organized way and lets you search and change it quickly, even when many people use it at once. The backend keeps in it whatever needs to last.Go to definition goes through 100,000 rows and throws them away. With a cursor, it jumps to the id with an index, like a book’s.
The offset is for lists that hardly change and where you want to jump between pages, like a catalog. For the ones that grow while they’re being read, like orders or messages, the cursor.
The Link header says where the next page is
Section titled “The Link header says where the next page is”What’s missing is telling the client how to ask for the next page. GitHub does it with a HeaderInformation a protocol puts in front of its data to do its job. In HTTP they are text lines of the form “Name: value”, such as Host or Content-Type; in TCP or IP they are numbers in fixed positions, such as ports or addresses.Go to definition, the link you saw in the introduction. Ask again for the two most recent open issues of Node.js, now with their title:
GitHub's first page and its Link header
curl -sI 'https://api.github.com/repos/nodejs/node/issues?per_page=2' | grep -i '^link'curl -s 'https://api.github.com/repos/nodejs/node/issues?per_page=2' | jq -c '.[] | {number, title}'What you will see:
link: <https://api.github.com/repositories/27193779/issues?per_page=2&after=Y3Vyc29yOnYyOpLPAAABoTU4rEjPAAAAAVuCfJw%3D&page=2>; rel="next"{"number":66705,"title":"test: deflake test-net-autoselectfamily-local-port"}{"number":66704,"title":"tools: update OpenSSL on the selected branch"}jq (lesson 8 of Phase 3) takes the number and the title out of each issue. Notice after=: GitHub’s cursor. Issues change every day, so your numbers and cursors will be different. If you get API rate limit exceeded, you’ve used up the 60 requests per hour GitHub gives without an account: wait.
The Link header is defined by RFC 8288: a URL between < and >, and in rel, its relation to this response. next is the next one; there are also prev, first and last. Copy the URL from your link and request it:
Follow GitHub's link
curl -si 'https://api.github.com/repositories/27193779/issues?per_page=2&after=Y3Vyc29yOnYyOpLPAAABoTU4rEjPAAAAAVuCfJw%3D&page=2' | grep -i '^link'curl -s 'https://api.github.com/repositories/27193779/issues?per_page=2&after=Y3Vyc29yOnYyOpLPAAABoTU4rEjPAAAAAVuCfJw%3D&page=2' | jq -c '.[] | {number, title}'What you will see:
link: <https://api.github.com/repositories/27193779/issues?per_page=2&after=Y3Vyc29yOnYyOpLPAAABoTSeNVDPAAAAAVtgJ8I%3D&page=3>; rel="next", <https://api.github.com/repositories/27193779/issues?per_page=2&page=1&before=Y3Vyc29yOnYyOpLPAAABoTUSnhjPAAAAAVt5sXQ%3D>; rel="prev"{"number":66702,"title":"stream: trim webstreams sink wrappers and BYOB transfers"}{"number":66700,"title":"deps: V8: cherry-pick 99f317d69ac7"}Two links, separated by a comma: next, with a new cursor, and prev, with before=. 66703 and 66701 are missing: they’re closed, and this list only brings the open ones.
The client doesn’t build the URL: it follows it. If GitHub changes its cursors, whoever follows next doesn’t notice. The shop also returns the whole URL:
// The Link header (RFC 8288) says where the next page is: the same URL, with another cursor.// The client doesn't have to build it, only follow it.export function nextLink(currentUrl: string, parameter: string, value: string): string { const url = new URL(currentUrl); url.searchParams.set(parameter, value); return `<${url.href}>; rel="next"`;}new URL(currentUrl) separates the parts of the URL, as in lesson 4 of Phase 3, and searchParams.set changes or adds a parameter without touching the others: if the request carried a filter, so does the link.
Other APIs say it in the body: Stripe sends has_more, and the client asks for the next page with the id of the last item in starting_after. The shop uses Link so that GET /orders keeps returning a list.
The route, with both ways
Section titled “The route, with both ways”To have something to paginate, src/data.ts creates 25 sample orders at startup:
// 25 sample orders, so there's something to paginate. The oldest ones are already shipped; the// ones in the middle, paid; the newest ones, pending.for (let number = 1; number <= 25; number++) { const order = createOrder((number % 3) + 1, (number % 4) + 1); if (number <= 12) order.status = 'shipped'; else if (number <= 20) order.status = 'paid';}
// From newest to oldest: the highest id is the last one created. toSorted sorts a copy; the// original list doesn't change.export function ordersNewestFirst(): Order[] { return orders.toSorted((a, b) => b.id - a.id);}for (let number = 1; number <= 25; number++)repeats the block withnumberfrom 1 to 25: it starts at 1, keeps going while it’s 25 or less and adds 1 each time.%is the remainder of the division:(number % 3) + 1gives products 1, 2 and 3 in turn.toSortedsorts a copy of the list. Its function compares two orders: ifb.id - a.idis positive,bgoes first. The result: highest id first.
And the route uses one way or the other depending on what arrives:
// A page of orders, from newest to oldest. If there are more, the Link header says where the next// one is. ?offset= stays to compare the two ways of paginating.app.get('/orders', validate('query', orderListSchema), (c) => { const { limit, cursor, offset, status } = c.req.valid('query'); let list = ordersNewestFirst(); if (status !== undefined) list = list.filter((order) => order.status === status);
if (offset !== undefined) { const { page, next } = pageByOffset(list, limit, offset); if (next !== undefined) { c.header('Link', nextLink(c.req.url, 'offset', String(next))); } return c.json(page); }
const { page, next } = pageByCursor(list, limit, cursor); if (next !== undefined) c.header('Link', nextLink(c.req.url, 'cursor', next)); return c.json(page);});validate('query', orderListSchema)checks the query string, with the middleware from lesson 7 of Phase 3.- First it filters by status, if asked to, and then it paginates: the filter decides the list, and the page, the piece.
c.header('Link', …)adds the header if there’s a next page.c.req.urlis the request’s whole URL.
The offset is only there to compare: a real API would pick one way.
Filtering and sorting in the query string
Section titled “Filtering and sorting in the query string”Filtering and sorting go in the query string too. This is what GET /orders accepts:
// What can be asked for in GET /orders. Everything is optional: with nothing, the first page of 10.export const orderListSchema = z .object({ limit: z.coerce .number({ error: 'Must be a number' }) .int('Must be a whole number') .min(1, 'At least 1') .max(50, 'At most 50') .default(10), cursor: cursorSchema.optional(), offset: z.coerce .number({ error: 'Must be a number' }) .int('Must be a whole number') .min(0, 'At least 0') .optional(), status: z .enum(['pending', 'paid', 'shipped', 'cancelled'], { error: 'Must be pending, paid, shipped or cancelled', }) .optional(), }) .refine((query) => query.cursor === undefined || query.offset === undefined, { error: 'Use cursor or offset, not both', path: ['cursor'], });.default(10): iflimitdoesn’t arrive, it’s 10..max(50)is the maximum.statusonly admits the four that exist. Any other value gives a422: ignoring it would return all of them, and the client would think they’re what it asked for..refine(…)is a rule about two fields: cursor or offset, not both.pathsays which field gets the blame inerrors(lesson 2).
Products are sorted by price, and with a minus in front, -price, from highest to lowest: the habit of many APIs, like JSON:API (sort=-created).
app.get('/products', validate('query', filterSchema), (c) => { const { max, sort } = c.req.valid('query'); let list = products; if (max !== undefined) list = list.filter((product) => product.price <= max); // toSorted sorts a copy: the original list's order doesn't change. if (sort === 'price') list = list.toSorted((a, b) => a.price - b.price); if (sort === '-price') list = list.toSorted((a, b) => b.price - a.price); return c.json(list);});a.price - b.price puts the cheapest first; b.price - a.price, the most expensive. In src/schemas.ts, filterSchema only admits those two sort orders:
// What comes in the path and in the query string is always text: coerce turns it into a number.export const idSchema = z.object({ id: z.coerce.number({ error: 'Must be a number' }).int('Must be a whole number'),});
export const filterSchema = z.object({ max: z.coerce.number({ error: 'Must be a number' }).positive('Must be greater than 0').optional(), // price, from lowest to highest; -price, from highest to lowest. sort: z.enum(['price', '-price'], { error: 'Must be price or -price' }).optional(),});Sorting, and the cursor that carries the sort order
Section titled “Sorting, and the cursor that carries the sort order”Orders are paginated by id, which is unique and doesn’t change. To paginate products by price, the cursor would carry the price of the last one. And if two cost €20, “the ones over 20” skips the second. The cursor carries the value it’s sorted by and, to break ties, the id: “after €20, number 7.”
The total has a cost
Section titled “The total has a cost”“Page 3 of 1,200” requires counting everything that matches the filter, and with a lot of data, counting means going through all of it on every page. That’s why many APIs don’t give the total: GitHub doesn’t give it in this list, and Stripe only says has_more. In the shop, if Link arrives, there’s more; if not, you’re done.
Try it
Section titled “Try it”The goal: go through the orders in pages, make the offset repeat an order and check that the cursor doesn’t.
Prepare the project
Section titled “Prepare the project”You’re still in ~/backend-course/phase-3/shop-api, with the code from lesson 2. Write the changes:
- Create
src/pagination.ts, with the lineimport type { Order } from './data.ts';and, below it, the four blocks of that file you’ve seen. - In
src/data.ts, add the sample orders andordersNewestFirstat the end. - In
src/schemas.ts, importreadCursorfrom./pagination.ts, addsorttofilterSchemaand, at the end,cursorSchemaandorderListSchema. - In
src/app.ts, importordersNewestFirstinstead oforders,orderListSchemaand the three functions from./pagination.ts, and change theGET /productsandGET /ordersroutes.
The tests come in this lesson’s folder: from ~/backend-course/phase-3, curl -O https://backenddesdecero.com/practicas/shop-api/12-pagination.tar.gz and tar -xzf 12-pagination.tar.gz. If you get stuck, compare your code with the folder’s. Then, in your project:
1. The pagination tests
cp ../12-pagination/test/pagination.test.ts test/npm test -- test/pagination.test.tsWhat you will see:
> shop-api@1.0.0 test> node --env-file=test/.env --test test/pagination.test.ts
✔ with nothing: the 10 newest first, and a Link to the next page (10.482444ms)✔ the cursor is opaque: the id in base64url, which the server knows how to read (0.149624ms)✔ following Link goes through the 25 orders, without repeating or skipping any (3.270495ms)✔ the status filter is kept in the link to the next page (1.34304ms)✔ with offset, the link carries the next offset (0.941124ms)✔ what is not valid in the query string: 422, with each field (3.24562ms)✔ the products, sorted by price both ways and filtered (0.910915ms)✔ with offset, an order that arrives between two pages makes one show up twice (1.507331ms)✔ with a cursor, the order that arrives between two pages does not change the next one (0.98229ms)ℹ tests 9ℹ suites 0ℹ pass 9ℹ fail 0ℹ cancelled 0ℹ skipped 0ℹ todo 0ℹ duration_ms 231.062343-- tells npm that what comes after it is for the script: that way node --test runs only the new file. If you get does not provide an export named, an export is missing; if you get is not defined, an import. The outputs are from Node 26.11.1 and curl 8.14.1, on Linux; your times, request ids and dates will be different.
Go through the orders
Section titled “Go through the orders”Start the server with npm run dev and open another terminal.
2. The first page
curl -i 'localhost:3000/orders?limit=3'What you will see:
HTTP/1.1 200 OKcontent-type: application/jsonlink: <http://localhost:3000/orders?limit=3&cursor=MjM>; rel="next"vary: Originx-request-id: 355c1ae4-170b-4ad7-a69f-609560745d7dcontent-length: 169Date: Tue, 13 Oct 2026 15:38:56 GMTConnection: keep-aliveKeep-Alive: timeout=5
[{"id":25,"productId":2,"quantity":2,"status":"pending"},{"id":24,"productId":1,"quantity":1,"status":"pending"},{"id":23,"productId":3,"quantity":4,"status":"pending"}]From 25 to 23, and in link, the next page: cursor=MjM, order 23. The quotes are needed: without them, the shell takes the ? and the & for something else. If you get the whole list without link, the server is still running the old route: check whether npm run dev has restarted.
3. Follow the link
curl -i 'localhost:3000/orders?limit=3&cursor=MjM'What you will see:
HTTP/1.1 200 OKcontent-type: application/jsonlink: <http://localhost:3000/orders?limit=3&cursor=MjA>; rel="next"vary: Originx-request-id: df5ac3e3-f7c7-413a-8509-43cefd4e4d0econtent-length: 166Date: Tue, 13 Oct 2026 15:38:56 GMTConnection: keep-aliveKeep-Alive: timeout=5
[{"id":22,"productId":2,"quantity":3,"status":"pending"},{"id":21,"productId":1,"quantity":2,"status":"pending"},{"id":20,"productId":3,"quantity":1,"status":"paid"}]Right after 23, 22, and a new link with the cursor of order 20. A filter is kept in the link:
curl -si 'localhost:3000/orders?status=shipped&limit=5' | grep -i '^link'link: <http://localhost:3000/orders?status=shipped&limit=5&cursor=OA>; rel="next"Make the offset repeat an order
Section titled “Make the offset repeat an order”Now, the trap from the diagram. If you’ve created orders, your ids will be different: to go back to the 25 sample orders, stop the server with Ctrl + C and start it again.
4. A page, a new order and the next page
curl -s 'localhost:3000/orders?limit=5&offset=0' | jq -c 'map(.id)'curl -s --json '{"productId":1,"quantity":1}' localhost:3000/orders | jq .idcurl -s 'localhost:3000/orders?limit=5&offset=5' | jq -c 'map(.id)'What you will see:
[25,24,23,22,21]26[21,20,19,18,17]map(.id) takes each order’s id, and .id, the new order’s. Look at 21: it’s the last one on the first page and the first one on the second. The delivery company would prepare its parcel twice.
And check that the cursor doesn’t
Section titled “And check that the cursor doesn’t”5. The same, with the cursor
curl -s 'localhost:3000/orders?limit=5' | jq -c 'map(.id)'curl -si 'localhost:3000/orders?limit=5' | grep -i '^link'curl -s --json '{"productId":1,"quantity":1}' localhost:3000/orders | jq .idcurl -s 'localhost:3000/orders?limit=5&cursor=MjI' | jq -c 'map(.id)'What you will see:
[26,25,24,23,22]link: <http://localhost:3000/orders?limit=5&cursor=MjI>; rel="next"27[21,20,19,18,17]The first page starts with order 26 from the previous step. Order 27 arrives, and the next page carries on right after 22. Order 27 isn’t lost: it will show up in the next read.
Filters, sorting and values that aren’t valid
Section titled “Filters, sorting and values that aren’t valid”6. A limit and a cursor that aren't valid
curl -i 'localhost:3000/orders?limit=500&cursor=hello'What you will see:
HTTP/1.1 422 Unprocessable Entitycontent-type: application/problem+jsonvary: Originx-request-id: eafae9be-e4d6-4235-bd5e-fe1f59ccc546content-length: 266Date: Tue, 13 Oct 2026 15:39:01 GMTConnection: keep-aliveKeep-Alive: timeout=5
{"type":"https://shop.example/problems/invalid-data","title":"The data is not valid","status":422,"detail":"See \"errors\" for what is wrong with each field.","errors":[{"field":"limit","problem":"At most 50"},{"field":"cursor","problem":"The cursor is not valid"}]}The error from lesson 2, with one problem per field. With ?cursor=MjI&offset=10, the problem is Use cursor or offset, not both.
7. The products, sorted
curl -w '\n' 'localhost:3000/products?sort=-price'curl -w '\n' 'localhost:3000/products?sort=price&max=30'curl -w '\n' 'localhost:3000/products?sort=name'What you will see:
[{"id":3,"name":"Hoodie","price":35},{"id":1,"name":"T-shirt","price":20},{"id":2,"name":"Mug","price":8.5}][{"id":2,"name":"Mug","price":8.5},{"id":1,"name":"T-shirt","price":20}]{"type":"https://shop.example/problems/invalid-data","title":"The data is not valid","status":422,"detail":"See \"errors\" for what is wrong with each field.","errors":[{"field":"sort","problem":"Must be price or -price"}]}From highest to lowest; from lowest to highest, without the ones over €30; and a sort order the API can’t do, with a 422 that says which ones it can.
Challenge: make the offset skip an order. Ask for the pending orders 2 at a time and, between the first page and the second, cancel one from the first. Then repeat it with the cursor.Show answer
Restart the server. The pending ones are 21 to 25, and you cancel with POST /orders/:id/cancellation (lesson 1):
curl -s 'localhost:3000/orders?status=pending&limit=2&offset=0' | jq -c 'map(.id)'curl -s -X POST localhost:3000/orders/24/cancellation | jq -c '{id, status}'curl -s 'localhost:3000/orders?status=pending&limit=2&offset=2' | jq -c 'map(.id)'[25,24]{"id":24,"status":"cancelled"}[22,21]What about 23? When 24 was cancelled, it moved up to place 2, already read. With the cursor, on the same list (now 25, 23, 22 and 21):
curl -s 'localhost:3000/orders?status=pending&limit=2' | jq -c 'map(.id)'curl -si 'localhost:3000/orders?status=pending&limit=2' | grep -i '^link'curl -s -X POST localhost:3000/orders/25/cancellation | jq -c '{id, status}'curl -s 'localhost:3000/orders?status=pending&limit=2&cursor=MjM' | jq -c 'map(.id)'[25,23]link: <http://localhost:3000/orders?status=pending&limit=2&cursor=MjM>; rel="next"{"id":25,"status":"cancelled"}[22,21]The cursor points at 23, and what comes after 23 is still 22. With offset=2, only 21 would have come out.
You have already seen it
Section titled “You have already seen it”- Google’s results have numbered pages: on the second one, the URL carries
start=10, an offset. - Social networks’ infinite scroll asks for more when you reach the end, without page numbers: the list changes every second, and the usual thing is a cursor. You’ll see it as you scroll down, in the Network tab of DevTools (how to open them).
- An online shop’s filters, like size or “sort by price,” change the query string: if you share the URL, the other person sees the same list.
Common mistakes
Section titled “Common mistakes”- Not setting a maximum limit.
?limit=1000000is the whole list again. - Paginating with an offset a list that changes while it’s being read, like orders or messages: use a cursor.
- Making up the cursor in the client. Follow
Link, or send back the cursor the API gives you as it is: it’s opaque and its format can change. - A cursor with a value that repeats, like the price, without the id to break ties: items get skipped.
- Ignoring a filter or a sort order you don’t understand. The client believes the list is the one it asked for: better a
422that says what’s accepted.
Summary
Section titled “Summary”- An API returns its lists in pages, with a limit the client asks for and a maximum the server sets.
- The offset counts positions: it lets you jump to any page, but if the list changes, it repeats or skips items, and with millions of rows it’s slow.
- The cursor points at the last item read and carries on right after it even if the list changes. It’s opaque: the client sends it back without interpreting it.
- The
Linkheader (RFC 8288) gives the next page’s URL withrel="next"; when it doesn’t arrive, you’ve finished. - Filters and sorting go in the query string, validated. To paginate a sorted list, the cursor carries the value it’s sorted by and the id.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- Using pagination in the REST API (GitHub): its
Linkheader andper_page. - RFC 8288: Web Linking: the
Linkheader and its relations. - Link (MDN): the header, with examples.
- Pagination (Stripe): another API with a cursor, with
starting_afterin the request andhas_morein the body. - Evolving API Pagination at Slack (Slack): why it moved from page numbers to cursors.