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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Always clamp user-supplied pagination values to sane bounds before touching the database.
- 2Running the page query and the count query in parallel with Promise.all keeps total latency down.
- 3Returning next/prev URLs makes an API self-describing so clients don't reconstruct pagination logic.
Related explainers
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
go
package middleware import ( "net/http"
Per-plan export limits in Gin middleware
middleware
rate-limiting
authorization
Intermediate
7 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
javascript
const { pool } = require('./db'); function withTransaction() { return async (req, res, next) => {
A per-request transaction middleware in Express
middleware
database-transactions
connection-pooling
Advanced
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-paginated-articles-endpoint-in-express-explained-javascript-c719/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.