5 min read
ā¢Question 14 of 28mediumWhat are different pagination techniques?
Understanding API pagination methods.
What You'll Learn
- Offset pagination
- Cursor pagination
- When to use each
1. Offset Pagination
code.jsJavaScript
GET /users?page=2&limit=20
// or
GET /users?offset=20&limit=20
// Response
{
"data": [...],
"meta": {
"page": 2,
"limit": 20,
"total": 150,
"totalPages": 8
}
}Pros: Simple, allows jumping to any page Cons: Inconsistent with real-time data, slow for large offsets
2. Cursor Pagination
code.jsJavaScript
GET /users?cursor=abc123&limit=20
// Response
{
"data": [...],
"meta": {
"nextCursor": "xyz789",
"prevCursor": "abc122",
"hasMore": true
}
}Pros: Consistent results, fast for any position Cons: Can't jump to specific page
Implementation
code.jsJavaScript
// Offset pagination
app.get('/users', async (req, res) => {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 20;
const offset = (page - 1) * limit;
const users = await User.find().skip(offset).limit(limit);
const total = await User.countDocuments();
res.json({ data: users, meta: { page, limit, total } });
});
// Cursor pagination
app.get('/users', async (req, res) => {
const { cursor, limit = 20 } = req.query;
const query = cursor ? { _id: { $gt: cursor } } : {};
const users = await User.find(query).limit(limit + 1);
const hasMore = users.length > limit;
res.json({
data: users.slice(0, limit),
meta: { nextCursor: users[limit - 1]?._id, hasMore }
});
});