Sequence NODE_249
MediumImplement Pagination on a List Endpoint
Express.js
Node.js
Technical Specification
Add pagination support to GET /items using query params page and limit.
Input/Output Samples
Input:GET /items?page=2&limit=5
Output:5 items from index 5–9
Optimal Logic Path
app.get("/items", (req, res) => {
const page = Math.max(1, Number(req.query.page) || 1);
const limit = Math.max(1, Number(req.query.limit) || 10);
const start = (page - 1) * limit;
const data = items.slice(start, start + limit);
const total = items.length;
const totalPages = Math.ceil(total / limit);
res.json({ data, page, total, totalPages });
});Architectural Deep-Dive
We calculate an offset based on page and limit, slice the data, and send helpful pagination metadata.