JAVASCRIPT

Client-Side API Pagination with Link Headers

Implement client-side pagination for APIs by parsing 'Link' HTTP headers (often used for HATEOAS) to navigate through paginated results like 'next', 'prev', 'first', and 'last' pages.

async function fetchPaginatedData(url) {
  try {
    const response = await fetch(url);

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    const data = await response.json();
    const linkHeader = response.headers.get('Link');

    let paginationLinks = {};
    if (linkHeader) {
      linkHeader.split(', ').forEach(link => {
        const parts = link.split(';');
        const urlMatch = parts[0].match(/<(.*)>/);
        const relMatch = parts[1].match(/rel="(.*)"/);

        if (urlMatch && relMatch) {
          paginationLinks[relMatch[1]] = urlMatch[1];
        }
      });
    }

    return { data, paginationLinks };

  } catch (error) {
    console.error("Error fetching paginated data:", error);
    throw error;
  }
}

// Example Usage:
// async function loadPage(pageUrl = 'https://api.example.com/items?page=1&per_page=10') {
//   try {
//     const { data, paginationLinks } = await fetchPaginatedData(pageUrl);
//     console.log('Current page data:', data);
//     console.log('Pagination links:', paginationLinks);

//     // Example of navigating to the next page
//     // if (paginationLinks.next) {
//     //   console.log('Loading next page...');
//     //   await loadPage(paginationLinks.next);
//     // }
//   } catch (error) {
//     console.error('Failed to load page:', error.message);
//   }
// }

// loadPage();
How it works: This JavaScript snippet provides a client-side solution for consuming paginated API data, specifically by parsing the `Link` HTTP header. Many RESTful APIs use this header to provide URLs for 'next', 'prev', 'first', and 'last' pages. The code fetches data, then extracts and parses the `Link` header to make these navigation URLs available, allowing developers to easily build pagination UI components.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs