Pagination and prefetching
createSwrPaginatedCache from swr-redis/pagination caches one page per
key and optionally prefetches following pages in the same write. It returns a
regular SwrCache<SwrPaginatedPage<TItem>, Context>. The example builds on
swr from getting started.
Cache paginated queries
Section titled “Cache paginated queries”import { createSwrPaginatedCache } from 'swr-redis/pagination'
interface Product { id: string name: string createdAt: Date}
interface ProductQuery { categoryId: string pageIndex: number}
const products = createSwrPaginatedCache(swr, { name: 'products', pageSize: 20, prefetchPages: 2, ttl: 120, pageIndex: (query: ProductQuery) => query.pageIndex, key: ({ context, pageIndex, pageSize }) => `products:${context.categoryId}:p${pageIndex}:s${pageSize}`, fetch: async (query, { skip, limit }, { signal }) => { const [docs, totalDocs] = await Promise.all([ db.findProducts(query.categoryId, { skip, limit, signal }), db.countProducts(query.categoryId, { signal }), ]) return { docs, totalDocs } },})
const page0 = await products.get({ categoryId: 'shoes', pageIndex: 0 })const page1 = await products.get({ categoryId: 'shoes', pageIndex: 1 })Reading page 0 fetches up to 60 items and caches pages 0, 1, and 2, so
reading page 1 is a cache hit.
Each cached page has the shape { docs, pageIndex, pageSize, totalDocs? }.
fetch can return { docs, totalDocs? }, a plain TItem[], or either wrapped
in SwrNoCache. totalDocs is included on cached pages only when fetch
returns it.
Pagination rules
Section titled “Pagination rules”- Keep
pageIndexandpageSizepure. Both run to build the key and again insidefetch.pageIndexis 0-based;pageSizecan be a number or(context) => number. - Build keys from all inputs.
key({ context, pageIndex, pageSize })runs for the requested page and every prefetched page. UsepageIndexandpageSizefrom the input (notcontext) so prefetched pages get distinct keys, and include every filter and sort field fromcontext. - Sort with a unique tiebreaker. End your
ORDER BYwith a unique column such asidso tied rows stay in a stable order across queries. Note that offset pagination can still shift rows between pages when rows are inserted or deleted. - Stay within safe integers.
prefetchPagesdefaults to0.pageIndex * pageSize,pageSize * (1 + prefetchPages), andpageIndex + prefetchPagesmust be safe integers orSwrValidationErroris thrown.
Prefetching
Section titled “Prefetching”When prefetchPages > 0, fetch receives skip = pageIndex * pageSize and
limit = pageSize * (1 + prefetchPages). The first pageSize items form the
requested page; remaining items are sliced into up to prefetchPages additional
pages and committed via SwrWriteBatch.
Trailing empty pages are not written.
- All written pages share
totalDocs, the requested page’sttlandstale,codec, andcompression. - During a fallback fetch
(
cacheWrite: 'skip'),fetchreceiveslimit = pageSizeand returns only the requested page. - Returning
SwrNoCachedelivers the requested page and caches none of the pages.