javascript
24 lines · 6 steps
Cursor-based pagination with fetch
An async loop walks every page of a cursor-paginated API and collects all rows into one array.
Explained by
highlit
1async function fetchAllPages(baseUrl, { pageSize = 100, headers = {} } = {}) {
2 const results = [];
3 let cursor = null;
4
5 do {
6 const url = new URL(baseUrl);
7 url.searchParams.set('limit', String(pageSize));
8 if (cursor) url.searchParams.set('cursor', cursor);
9
10 const res = await fetch(url, {
11 headers: { Accept: 'application/json', ...headers },
12 });
13
14 if (!res.ok) {
15 throw new Error(`Request failed: ${res.status} ${res.statusText}`);
16 }
17
18 const { data, next_cursor: nextCursor } = await res.json();
19 results.push(...data);
20 cursor = nextCursor ?? null;
21 } while (cursor);
22
23 return results;
24}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A do/while loop is ideal for pagination since you always need at least one request before knowing if more pages exist.
- 2Cursor pagination chains requests by feeding each response's next cursor into the following call until it runs dry.
- 3Building a URL with URLSearchParams keeps query parameters safely encoded and conditional ones easy to add.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/cursor-based-pagination-with-fetch-explained-javascript-5f55/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.