next.js: Using dompurify with SSR or Server Component fails with webpack error
Verify canary release
- I verified that the issue exists in the latest Next.js canary release
Provide environment information
Operating System:
Platform: linux
Arch: x64
Version: #22 SMP Tue Jan 10 18:39:00 UTC 2023
Binaries:
Node: 16.17.0
npm: 8.15.0
Yarn: 1.22.19
pnpm: 7.1.0
Relevant packages:
next: 13.2.4-canary.5
eslint-config-next: N/A
react: 18.2.0
react-dom: 18.2.0
Which area(s) of Next.js are affected? (leave empty if unsure)
App directory (appDir: true)
Link to the code that reproduces this issue
https://codesandbox.io/p/sandbox/angry-thunder-s7tvqk?file=%2Fapp%2Fpage.tsx
To Reproduce
- Open the CodeSandbox above, main code is this in
app/page.tsximport DOMPurify from "dompurify"; export default function Home() { return ( <div dangerouslySetInnerHTML={{ // π₯ Error: dompurify__WEBPACK_IMPORTED_MODULE_1___default(...).sanitize is not a function __html: DOMPurify.sanitize("<img src=x onerror=alert(1)//>"), }} /> ); } - Observe the error message below
Error: dompurify__WEBPACK_IMPORTED_MODULE_1___default(...).sanitize is not a function

This kind of works in the pages/ directory (the image appears in the browser), although still throws an error while rendering in SSR.
Describe the Bug
It seems that the dompurify library does not support Node.js usage out of the box.
One recommendation from Stack Overflow is to use isomorphic-dompurify (300k weekly downloads vs 3.5m for dompurify)
Expected Behavior
dompurify works out of the box with Next.js and Node.js
Related issues
Which browser are you using? (if relevant)
No response
How are you deploying your application? (if relevant)
No response
About this issue
- Original URL
- State: closed
- Created a year ago
- Comments: 18 (18 by maintainers)
ohh π Itβs the XSS payload
<img src=x onerror=alert(1)//>lolThis can also be reproduced without DOMPurify, like this:
The 404 will cause the error page to be rendered:
Thanks for the PR and merge @JesseKoldewijn @ijjk ! π From a first look, seems like
next@13.2.5-canary.1is working:CodeSandbox demo: https://codesandbox.io/p/sandbox/quirky-gagarin-speccj?file=%2Fapp%2Fpage.tsx
Will do! π
cc @JesseKoldewijn, in case this approach is accepted by the team and you want to get another PR in for Next.js!