How to Implement Pagination in Express API Easily
To implement pagination in an
Express API, use query parameters like page and limit to control which data slice to return. Calculate the starting index with (page - 1) * limit and use Array.slice() or database queries with skip and limit to return the correct items.Syntax
Pagination in Express API typically uses two query parameters:
- page: The current page number (starts at 1).
- limit: The number of items to show per page.
Calculate the starting index as (page - 1) * limit. Then return items from that index up to limit count.
javascript
app.get('/items', (req, res) => { const page = parseInt(req.query.page) || 1; const limit = parseInt(req.query.limit) || 10; const startIndex = (page - 1) * limit; const endIndex = page * limit; const results = data.slice(startIndex, endIndex); res.json(results); });
Example
This example shows a simple Express API endpoint that returns paginated items from an array. It reads page and limit from the query string, calculates the slice of data to return, and sends it as JSON.
javascript
import express from 'express'; const app = express(); const port = 3000; const data = Array.from({ length: 50 }, (_, i) => ({ id: i + 1, name: `Item ${i + 1}` })); app.get('/items', (req, res) => { const page = parseInt(req.query.page) || 1; const limit = parseInt(req.query.limit) || 10; const startIndex = (page - 1) * limit; const endIndex = page * limit; const results = data.slice(startIndex, endIndex); res.json({ page, limit, results }); }); app.listen(port, () => { console.log(`Server running on http://localhost:${port}`); });
Output
{"page":2,"limit":5,"results":[{"id":6,"name":"Item 6"},{"id":7,"name":"Item 7"},{"id":8,"name":"Item 8"},{"id":9,"name":"Item 9"},{"id":10,"name":"Item 10"}]}
Common Pitfalls
Common mistakes when implementing pagination include:
- Not validating
pageandlimitvalues, which can cause errors or unexpected results. - Using zero-based page numbers instead of starting at 1, confusing users.
- Not handling cases where
pageorlimitare missing or invalid. - Returning all data without slicing, which defeats pagination.
javascript
app.get('/items', (req, res) => { // Wrong: no validation, zero-based page const page = parseInt(req.query.page) || 0; // should start at 1 const limit = parseInt(req.query.limit) || 10; const startIndex = (page - 1) * limit; // corrected calculation const results = data.slice(startIndex, startIndex + limit); res.json(results); }); // Corrected version app.get('/items', (req, res) => { let page = parseInt(req.query.page); let limit = parseInt(req.query.limit); if (!page || page < 1) page = 1; if (!limit || limit < 1) limit = 10; const startIndex = (page - 1) * limit; const endIndex = page * limit; const results = data.slice(startIndex, endIndex); res.json({ page, limit, results }); });
Quick Reference
Tips for smooth pagination in Express API:
- Always parse and validate
pageandlimitquery parameters. - Start page numbering at 1 for user friendliness.
- Calculate start index as
(page - 1) * limit. - Use
slicefor arrays orskipandlimitin database queries. - Return metadata like current page and limit along with results.
Key Takeaways
Use query parameters 'page' and 'limit' to control pagination in Express API.
Calculate the starting index as (page - 1) * limit to slice data correctly.
Always validate and default 'page' and 'limit' to avoid errors.
Return paginated data along with metadata like current page and limit.
Handle missing or invalid query parameters gracefully for better user experience.