javascript / expert
Snippet
Sanitizing Server-Side HTML Rendering via DOMPurify and JSDOM in Next.js App Router
Executing headless JSDOM DOMPurify instances within Next.js Server Components enables strict server-side HTML markup sanitization prior to rendering untrusted content with dangerouslySetInnerHTML.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { JSDOM } from 'jsdom';import DOMPurify from 'dompurify';const window = new JSDOM('').window;const purify = DOMPurify(window);export function sanitizeHtmlPayload(dirtyHtml) {if (typeof dirtyHtml !== 'string') {throw new TypeError('Payload must be a string');}return purify.sanitize(dirtyHtml, {ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a'],ALLOWED_ATTR: ['href']});}
nextjs
Breakdown
1
const window = new JSDOM('').window;
Instantiates a minimal virtual DOM window instance in Node.js server memory.
2
const purify = DOMPurify(window);
Binds DOMPurify sanitizer functions to the isolated virtual DOM instance.
3
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a'],
Defines an explicit whitelist of safe markup elements, stripping out script or iframe tags.