Pagination helps split large data into smaller parts so users can see it page by page. It makes apps faster and easier to use.
Pagination patterns in 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.
const page = 2; const limit = 5; const offset = (page - 1) * limit; // Fetch items 6 to 10
const page = 1; const limit = 20; const offset = 0; // Fetch first 20 items
const cursor = 'abc123'; // Use cursor for cursor-based pagination instead of offset
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.
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'); });
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.
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.
Practice
What is the main purpose of pagination in a Node.js application?
Solution
Step 1: Understand pagination concept
Pagination divides data into smaller chunks or pages to avoid loading everything at once.Step 2: Identify the benefit in Node.js apps
This improves speed and usability by sending only a subset of data per request.Final Answer:
To split large data into smaller pages for faster loading and better user experience -> Option BQuick Check:
Pagination = split data for speed [OK]
- Thinking pagination deletes data
- Confusing pagination with encryption
- Assuming pagination combines all data
Which of the following is the correct way to use limit and offset for pagination in a SQL query within Node.js?
SELECT * FROM users ORDER BY id ASC LIMIT ? OFFSET ?;
Solution
Step 1: Understand limit and offset roles
Limit controls how many items to fetch; offset skips items before starting.Step 2: Calculate offset for pagination
Offset should skip items from previous pages: (page number - 1) * items per page.Final Answer:
limit = number of items per page, offset = (page number - 1) * number of items per page -> Option AQuick Check:
Offset skips previous pages = (page-1)*limit [OK]
- Using offset as page number directly
- Swapping limit and offset values
- Setting offset to page number without calculation
Given this Node.js code snippet using a database query for pagination:
const page = 3;
const limit = 10;
const offset = (page - 1) * limit;
const results = await db.query('SELECT * FROM products ORDER BY id ASC LIMIT ? OFFSET ?', [limit, offset]);
console.log(results.length);If the database has 25 products, what will results.length print?
Solution
Step 1: Calculate offset and limit values
Page 3 means offset = (3-1)*10 = 20, limit = 10.Step 2: Determine how many products remain after offset
There are 25 products total, offset 20 skips first 20, leaving 5 products.Final Answer:
5 -> Option DQuick Check:
Remaining items after offset = 5 [OK]
- Assuming full limit items always returned
- Calculating offset incorrectly
- Ignoring total number of products
Identify the error in this Node.js pagination code snippet:
const page = 0;
const limit = 10;
const offset = page * limit;
const results = await db.query('SELECT * FROM items LIMIT ? OFFSET ?', [limit, offset]);What is the problem with this code?
Solution
Step 1: Check page number usage
Page is set to 0, but pagination usually starts at 1.Step 2: Calculate offset impact
Offset = 0 * 10 = 0, so it fetches first page, but page 0 is invalid logically.Final Answer:
Page number should start from 1, not 0, causing incorrect offset -> Option CQuick Check:
Page numbering starts at 1 [OK]
- Using page 0 as valid page
- Setting limit to zero incorrectly
- Misunderstanding offset calculation
You want to implement cursor-based pagination in Node.js for a real-time chat app. Which approach is best to fetch the next page of messages?
// Current last message ID is stored in lastMessageId
const query = 'SELECT * FROM messages WHERE id < ? ORDER BY id DESC LIMIT ?';
const results = await db.query(query, [lastMessageId, limit]);Why is this approach better than using offset?
Solution
Step 1: Understand cursor pagination
Cursor uses a unique ID to fetch next items after the last seen message.Step 2: Compare with offset pagination
Offset can skip or repeat items if data changes during pagination; cursor avoids this.Final Answer:
Cursor pagination avoids skipping items and handles new data better than offset -> Option AQuick Check:
Cursor = stable pagination with changing data [OK]
- Thinking offset is better for real-time data
- Assuming cursor is less reliable
- Confusing cursor with offset usage
Ready to prove it?
Pass the test and this pattern moves unknown
