URL filtering and pagination
URL state lets learners share a filtered catalog or return to it later. Treat the URL as the source for display options, validate each field, and choose explicit defaults. Here sorting accepts title or price; page accepts whole decimal numbers from 1 to 100. Duplicate values are rejected to defaults.
Scope: Next.js 16.x candidate, App Router only, Cache Components disabled, TypeScript unless otherwise labeled. Examples are static source walkthroughs; exact framework patch and build are not verified.
lib/catalog-query.js (pure JavaScript helper)
export function parseCatalogQuery(query) { const sort = query.sort === 'price' ? 'price' : 'title'; const raw = query.page; const page = typeof raw === 'string' && /^[1-9]\d{0,2}$/.test(raw) && Number(raw) <= 100 ? Number(raw) : 1; return { sort, page };}For {sort: "price", page: "2"} the result is {sort: "price", page: 2}. For {sort: ["price", "title"], page: "1e2"} the result is {sort: "title", page: 1}. The regex permits one to three decimal digits starting with 1–9, then the numerical limit rejects values above 100.
Sort before slicing
Validate first, then order the data with a deterministic tie breaker, then slice the requested page. The sample titles are unique; real records can share titles and prices. Add an immutable unique ID as the final sort key for database paging, and remember that concurrent inserts can still shift offset pages. The page number limit is an example resource bound, not a rule of Next.js. A syntactically valid page may still exceed the available dataset; this lesson chooses an empty result with a recovery link rather than silently clamping. Preserve the chosen sort in pagination links and reset the page when changing sort.
A pure paging example (partial JavaScript)
const books = [{title:'Moss',price:12},{title:'Harbor',price:8},{title:'Dawn',price:8}];const { sort, page } = parseCatalogQuery({sort:'price',page:'2'});const ordered = [...books].sort((a,b) => (sort === 'price' ? a.price - b.price : 0) || (a.title < b.title ? -1 : a.title > b.title ? 1 : 0));console.log(ordered.slice((page-1)*2, page*2).map(b => b.title));Expected console result: ["Moss"]. Dawn and Harbor tie on price, so title ordering breaks the tie. A copy is sorted, leaving the original array unchanged.
Common mistake
Do not use parseInt alone for strict page validation: it can accept a valid prefix of invalid text. Do not use a query sort field as an unchecked database column or let unlimited page numbers trigger unbounded work.
Try it yourself
For a price-sorted catalog on page 2, construct /catalog?sort=price&page=1 as the previous link. Predict the parser output for empty, repeated and out-of-range values.
After this lesson, you should be able to: Validate sort and page inputs; Preserve a shareable URL.