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
const express = require('express'); const router = express.Router(); const { pool } = require('../db'); const redis = require('../redis');
Building a health check endpoint in Express
health-check
timeouts
promise-race
Intermediate
9 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
Intermediate
8 steps
java
@Repository public interface OrderRepository extends JpaRepository<Order, Long> { @Query("""
Keyset pagination with Spring Data JPA
pagination
cursor
jpa
Advanced
8 steps
javascript
const MAX_BATCH_SIZE = 20; const FLUSH_INTERVAL = 5000; const ENDPOINT = '/api/analytics';
Batching analytics events in the browser
batching
buffering
sendbeacon
Intermediate
10 steps
javascript
export function diffIds(current, desired) { const currentSet = new Set(current); const desiredSet = new Set(desired);
Diffing sets to sync group membership
set-operations
diffing
transactions
Intermediate
8 steps
javascript
class HistoryStack { constructor(initial = '', limit = 100) { this.past = []; this.present = initial;
Building an undo/redo history stack
undo-redo
state-management
debouncing
Intermediate
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.