Deviopath › Next.js

Pagination Links

Medium · Search Params

Paginated lists usually keep the page number in the URL (/blog?page=2), so every page can be shared and the Back button works. When you build the links you must keep the other search params (filters, search text) and only change page.

Write paginationHrefs(pathname, search, totalPages). search is the query string without ? (maybe empty). Return { current, prev, next, pages }:

- current is the page param when it is a whole number. A missing or non-whole value means page 1. Values below 1 become 1 and values above totalPages become totalPages.

- The href for page p: copy the params, set("page", p), except for page 1 where you delete("page") so the first page has a clean URL. Use URLSearchParams so the order and encoding match (set keeps an existing key in its place, new keys go last, spaces become +). If no params are left the href is just pathname, otherwise pathname + "?" + params.

- prev / next are the hrefs of the neighbouring pages, or null on the first / last page.

- pages lists the hrefs of pages 1 to totalPages in order.

Next: Filter and Sort with searchParams