How to Implement Pagination in Node.js: Simple Guide
To implement pagination in
Node.js, use query parameters like page and limit to control which data slice to fetch. Calculate the skip value as (page - 1) * limit and use it with your database query to return only the needed records.Syntax
Pagination in Node.js typically uses two query parameters: page (current page number) and limit (items per page). You calculate skip to tell the database how many items to skip before starting to return results.
- page: Which page of results to show (starts at 1).
- limit: How many items to show per page.
- skip: Number of items to skip, calculated as
(page - 1) * limit.
javascript
const page = parseInt(req.query.page) || 1; const limit = parseInt(req.query.limit) || 10; const skip = (page - 1) * limit; // Example with MongoDB const results = await collection.find().skip(skip).limit(limit).toArray();
Example
This example shows a simple Express.js route that returns paginated user data from a MongoDB collection. It reads page and limit from the query string, calculates skip, and fetches only the requested slice of users.
javascript
import express from 'express'; import { MongoClient } from 'mongodb'; const app = express(); const client = new MongoClient('mongodb://localhost:27017'); async function main() { await client.connect(); const db = client.db('testdb'); const users = db.collection('users'); app.get('/users', async (req, res) => { const page = parseInt(req.query.page) || 1; const limit = parseInt(req.query.limit) || 5; const skip = (page - 1) * limit; const results = await users.find().skip(skip).limit(limit).toArray(); res.json({ page, limit, results }); }); app.listen(3000, () => console.log('Server running on http://localhost:3000')); } main().catch(console.error);
Output
{"page":1,"limit":5,"results":[{"_id":"...","name":"User1"},{"_id":"...","name":"User2"},{"_id":"...","name":"User3"},{"_id":"...","name":"User4"},{"_id":"...","name":"User5"}]}
Common Pitfalls
Common mistakes when implementing pagination include:
- Not validating
pageandlimitvalues, which can cause errors or performance issues. - Using
skipwith very large offsets, which can slow down database queries. - Not returning total count or next page info, making it hard for clients to know when to stop.
Always sanitize inputs and consider adding total count for better UX.
javascript
/* Wrong: No validation, can cause negative skip */ const page = parseInt(req.query.page); const limit = parseInt(req.query.limit); const skip = (page - 1) * limit; // if page=0, skip=-limit (bad) /* Right: Validate and set defaults */ const pageSafe = Math.max(parseInt(req.query.page) || 1, 1); const limitSafe = Math.min(Math.max(parseInt(req.query.limit) || 10, 1), 100); // max 100 const skipSafe = (pageSafe - 1) * limitSafe;
Quick Reference
Summary tips for pagination in Node.js:
- Use
pageandlimitquery parameters. - Calculate
skip = (page - 1) * limitfor database queries. - Validate and sanitize inputs to avoid errors.
- Return total count or next page info for better client experience.
- Consider performance impact of large
skipvalues.
Key Takeaways
Use query parameters page and limit to control pagination in Node.js.
Calculate skip as (page - 1) * limit to fetch the correct data slice.
Always validate and sanitize page and limit values to avoid errors.
Return total count or next page info to help clients navigate pages.
Be aware that large skip values can slow down database queries.