0
0
Node.jsframework~5 mins

Pagination patterns in Node.js

Choose your learning style9 modes available
Introduction

Pagination helps split large data into smaller parts so users can see it page by page. It makes apps faster and easier to use.

Showing a list of products in an online store with many items.
Displaying search results that have hundreds or thousands of entries.
Loading user comments on a blog post without slowing down the page.
Showing messages in a chat app where new messages keep coming.
Fetching data from a database in small chunks to save memory.
Syntax
Node.js
const page = 1; // current page number
const limit = 10; // items per page
const offset = (page - 1) * limit;

// Use offset and limit in database query
const results = await db.query('SELECT * FROM items LIMIT ? OFFSET ?', [limit, offset]);

offset tells where to start fetching data.

limit controls how many items to get per page.

Examples
This fetches the second page with 5 items per page.
Node.js
const page = 2;
const limit = 5;
const offset = (page - 1) * limit;
// Fetch items 6 to 10
This fetches the first page with 20 items.
Node.js
const page = 1;
const limit = 20;
const offset = 0;
// Fetch first 20 items
Cursor pagination uses a marker to fetch next items, useful for real-time data.
Node.js
const cursor = 'abc123';
// Use cursor for cursor-based pagination instead of offset
Sample Program

This Node.js Express app serves a list of 50 items with pagination. You can request pages with query parameters like ?page=2&limit=5. It returns the current page, limit, total items, total pages, and the items for that page.

Node.js
import express from 'express';
const app = express();

const items = Array.from({ length: 50 }, (_, i) => `Item ${i + 1}`);

app.get('/items', (req, res) => {
  const page = Number(req.query.page) || 1;
  const limit = Number(req.query.limit) || 10;
  const offset = (page - 1) * limit;

  const pagedItems = items.slice(offset, offset + limit);

  res.json({
    page,
    limit,
    totalItems: items.length,
    totalPages: Math.ceil(items.length / limit),
    data: pagedItems
  });
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Always validate page and limit values to avoid errors or too large queries.

Cursor pagination is better for constantly changing data to avoid missing or repeating items.

Use indexes in your database to speed up pagination queries.

Summary

Pagination splits data into pages to improve speed and usability.

Use limit and offset for simple page-based pagination.

Cursor pagination is an alternative for real-time or large datasets.