javascript 50 lines · 8 steps

Building a paginated articles endpoint in Express

An Express route sanitizes pagination input, fetches a page of rows plus a total count in parallel, and returns navigable next/prev links.

Explained by highlit
1const express = require('express');
2const router = express.Router();
3const db = require('../db');
4 
5const MAX_LIMIT = 100;
6const DEFAULT_LIMIT = 20;
7 
8function parsePagination(query) {
9 let limit = parseInt(query.limit, 10);
10 let offset = parseInt(query.offset, 10);
11 
12 if (Number.isNaN(limit) || limit < 1) limit = DEFAULT_LIMIT;
13 if (limit > MAX_LIMIT) limit = MAX_LIMIT;
14 if (Number.isNaN(offset) || offset < 0) offset = 0;
15 
16 return { limit, offset };
17}
18 
19router.get('/articles', async (req, res, next) => {
20 try {
21 const { limit, offset } = parsePagination(req.query);
22 
23 const [rows, [{ total }]] = await Promise.all([
24 db.query(
25 'SELECT id, title, published_at FROM articles ORDER BY published_at DESC LIMIT ? OFFSET ?',
26 [limit, offset]
27 ),
28 db.query('SELECT COUNT(*) AS total FROM articles'),
29 ]);
30 
31 const baseUrl = `${req.protocol}://${req.get('host')}${req.baseUrl}${req.path}`;
32 const nextOffset = offset + limit;
33 const prevOffset = Math.max(offset - limit, 0);
34 
35 res.json({
36 data: rows,
37 pagination: {
38 total,
39 limit,
40 offset,
41 next: nextOffset < total ? `${baseUrl}?limit=${limit}&offset=${nextOffset}` : null,
42 prev: offset > 0 ? `${baseUrl}?limit=${limit}&offset=${prevOffset}` : null,
43 },
44 });
45 } catch (err) {
46 next(err);
47 }
48});
49 
50module.exports = router;
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Always clamp user-supplied pagination values to sane bounds before touching the database.
  2. 2Running the page query and the count query in parallel with Promise.all keeps total latency down.
  3. 3Returning next/prev URLs makes an API self-describing so clients don't reconstruct pagination logic.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a paginated articles endpoint in Express — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code