Pagination Implementation

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.
Development and maintenance of all types of websites:
Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Our competencies:
Development stages
Latest works
  • image_website-b2b-advance_0.png
    B2B ADVANCE company website development
    1212
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1161
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    852
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1041
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    822
  • image_bitrix-bitrix-24-1c_fixper_448_0.png
    Website development for FIXPER company
    815

Implementing Pagination on a Website

Pagination divides large data sets into fixed-size pages. It's a basic element of any site with a catalog, table, or publication feed. Implementation includes server-side (LIMIT/OFFSET requests), API contract, and UI navigation component.

Server-side

// Laravel — standard paginate()
public function index(Request $request): JsonResponse
{
    $perPage = min($request->integer('per_page', 20), 100);

    $products = Product::where('is_active', true)
        ->orderByDesc('created_at')
        ->paginate($perPage);

    return response()->json([
        'data'         => ProductResource::collection($products->items()),
        'current_page' => $products->currentPage(),
        'last_page'    => $products->lastPage(),
        'per_page'     => $products->perPage(),
        'total'        => $products->total(),
        'from'         => $products->firstItem(),
        'to'           => $products->lastItem(),
    ]);
}

API request: GET /api/products?page=3&per_page=20

Under the hood, Laravel executes two SQL queries: COUNT(*) for total and SELECT ... LIMIT 20 OFFSET 40. On tables with 500k+ rows, COUNT can slow down — solved via caching total or switching to approximate count via pg_class.reltuples.

UI Pagination Component

// components/Pagination.tsx
interface PaginationProps {
  currentPage: number
  lastPage: number
  onPageChange: (page: number) => void
}

export function Pagination({ currentPage, lastPage, onPageChange }: PaginationProps) {
  const pages = buildPageRange(currentPage, lastPage)

  return (
    <nav aria-label="Pagination">
      <ul className="flex items-center gap-1">
        <li>
          <button
            onClick={() => onPageChange(currentPage - 1)}
            disabled={currentPage === 1}
            aria-label="Previous page"
          >
            ←
          </button>
        </li>

        {pages.map((page, i) =>
          page === '...' ? (
            <li key={`ellipsis-${i}`} aria-hidden="true">…</li>
          ) : (
            <li key={page}>
              <button
                onClick={() => onPageChange(page as number)}
                aria-current={page === currentPage ? 'page' : undefined}
                className={page === currentPage ? 'font-bold' : ''}
              >
                {page}
              </button>
            </li>
          )
        )}

        <li>
          <button
            onClick={() => onPageChange(currentPage + 1)}
            disabled={currentPage === lastPage}
            aria-label="Next page"
          >
            →
          </button>
        </li>
      </ul>
    </nav>
  )
}

// Produces array like [1, 2, '...', 7, 8, 9, '...', 20]
function buildPageRange(current: number, last: number): (number | '...')[] {
  if (last <= 7) return Array.from({ length: last }, (_, i) => i + 1)

  const delta = 2
  const range: (number | '...')[] = []
  const left = current - delta
  const right = current + delta

  let prev: number | null = null
  for (let i = 1; i <= last; i++) {
    if (i === 1 || i === last || (i >= left && i <= right)) {
      if (prev !== null && i - prev > 1) range.push('...')
      range.push(i)
      prev = i
    }
  }
  return range
}

Sync with URL

Page number must live in URL — otherwise users lose position on page refresh and can't share links.

// Next.js App Router
'use client'
import { useRouter, useSearchParams, usePathname } from 'next/navigation'

function usePageParam() {
  const searchParams = useSearchParams()
  const router = useRouter()
  const pathname = usePathname()

  const page = Number(searchParams.get('page') ?? '1')

  const setPage = (newPage: number) => {
    const params = new URLSearchParams(searchParams.toString())
    params.set('page', String(newPage))
    router.push(`${pathname}?${params.toString()}`, { scroll: true })
  }

  return [page, setPage] as const
}
// Vanilla React — history API
function setPageInUrl(page: number) {
  const url = new URL(window.location.href)
  url.searchParams.set('page', String(page))
  window.history.pushState({}, '', url)
}

Prefetch Next Page

To make transitions feel instant, preload next page data:

import { useQueryClient } from '@tanstack/react-query'

function useProductsPrefetch(currentPage: number) {
  const queryClient = useQueryClient()

  useEffect(() => {
    if (currentPage < lastPage) {
      queryClient.prefetchQuery({
        queryKey: ['products', currentPage + 1],
        queryFn: () => fetchProducts(currentPage + 1),
        staleTime: 30_000,
      })
    }
  }, [currentPage])
}

SEO

For search bots, paginated pages should be properly linked:

<!-- On page /catalog?page=3 -->
<link rel="prev" href="/catalog?page=2" />
<link rel="next" href="/catalog?page=4" />
<link rel="canonical" href="/catalog?page=3" />

Google officially doesn't use rel=prev/next since 2019, but Yandex does. In Laravel Blade or Next.js Metadata API, output these tags.

Timeline

Basic component with API integration — 1 day. With URL sync, prefetch, SEO tags, and responsive display — 2 days.