Pagination with Claude Code: Cursor-Based vs OFFSET and Infinite Scroll
Source: Dev.to
Pagination Design Rules
Method
- Over 10,000 rows: cursor‑based required (OFFSET forbidden)
- Admin UIs with small datasets: OFFSET pagination acceptable
- Infinite scroll: cursor‑based +
hasNextPage
Cursor‑Based
- Cursor must be opaque (don’t expose internal structure to clients)
- Encode cursor as Base64 of ID or composite key
- Response includes
nextCursorandhasNextPage
Performance
- Enforce pageSize limit (max 100)
orderByrequired (needed for cursor‑based sorting)- Index cursor column
Generating Cursor Pagination
Endpoint: GET /api/users
Parameters: cursor?, limit (1‑100, default 20)
Response: { data: User[], nextCursor: string | null, hasNextPage: boolean }
Requirements
- Prisma cursor pagination
- Base64‑encode cursor
orderBy:createdAt desc,id desc(tiebreaker)
Generated Code
Pagination Utilities (src/utils/pagination.ts)
// src/utils/pagination.ts
export function encodeCursor(id: string, createdAt: Date): string {
return Buffer.from(
JSON.stringify({ id, createdAt: createdAt.toISOString() })
).toString('base64');
}
export function decodeCursor(cursor: string): { id: string; createdAt: Date } | null {
try {
const decoded = JSON.parse(
Buffer.from(cursor, 'base64').toString('utf-8')
);
return { id: decoded.id, createdAt: new Date(decoded.createdAt) };
} catch {
return null;
}
}
User Service (src/services/userService.ts)
// src/services/userService.ts
export async function listUsers(
limit: number,
cursor?: string
): Promise> {
const take = Math.min(limit, 100);
const decoded = cursor ? decodeCursor(cursor) : null;
const users = await prisma.user.findMany({
take: take + 1, // Fetch one extra to detect hasNextPage
...(decoded && {
cursor: { id: decoded.id },
skip: 1,
}),
orderBy: [
{ createdAt: 'desc' },
{ id: 'desc' }, // Tiebreaker for same timestamp
],
});
const hasNextPage = users.length > take;
const data = hasNextPage ? users.slice(0, take) : users;
const lastItem = data[data.length - 1];
return {
data,
nextCursor: lastItem ? encodeCursor(lastItem.id, lastItem.createdAt) : null,
hasNextPage,
};
}
Frontend Infinite Scroll
// useInfiniteUsers.ts
import { useInfiniteQuery } from '@tanstack/react-query';
export function useInfiniteUsers() {
return useInfiniteQuery({
queryKey: ['users'],
queryFn: ({ pageParam }) =>
fetch(`/api/users?limit=20${pageParam ? `&cursor=${pageParam}` : ''}`).then(r => r.json()),
getNextPageParam: (lastPage) => lastPage.hasNextPage ? lastPage.nextCursor : undefined,
initialPageParam: undefined,
});
}
function UserList() {
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useInfiniteUsers();
const ref = useRef(null);
// Trigger next page when bottom element comes into view
useIntersectionObserver(ref, () => {
if (hasNextPage && !isFetchingNextPage) fetchNextPage();
});
return (
<>
{data?.pages.flatMap(p => p.data).map(user => )}
);
}
OFFSET Pagination (Admin Panels Only)
// Only when direct page jumping is required
router.get('/admin/users', async (req, res) => {
const page = Math.max(1, Number(req.query.page) || 1);
const limit = 20;
const [total, users] = await prisma.$transaction([
prisma.user.count(),
prisma.user.findMany({
skip: (page - 1) * limit,
take: limit,
orderBy: { createdAt: 'desc' },
}),
]);
res.json({
data: users,
total,
page,
totalPages: Math.ceil(total / limit),
});
});
Summary
- CLAUDE.md – Cursor‑based required for 10k+ rows; OFFSET forbidden at scale.
- Base64 cursor – Hides internal structure from clients.
- take + 1 trick – Fetch one extra item to determine
hasNextPagewithout an extraCOUNTquery. - React Query
useInfiniteQuery– Built‑in infinite scroll with cursor support. - Code Review Pack (¥980) includes
/code-reviewto detect pagination issues – OFFSET at scale, unsafe cursor exposure, missing index.