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

  1. Open the CodeSandbox above, main code is this in app/page.tsx
    import 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)//>"),
          }}
        />
      );
    }
    
  2. Observe the error message below
Error: dompurify__WEBPACK_IMPORTED_MODULE_1___default(...).sanitize is not a function

Screenshot 2023-03-07 at 18 24 45

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)

Commits related to this issue

Most upvoted comments

ohh πŸ™ˆ It’s the XSS payload <img src=x onerror=alert(1)//> lol

This can also be reproduced without DOMPurify, like this:

export default function Home() {
  return <img src="x" />;
}

The 404 will cause the error page to be rendered:

Screenshot 2023-03-12 at 11 39 45

Thanks for the PR and merge @JesseKoldewijn @ijjk ! πŸ™Œ From a first look, seems like next@13.2.5-canary.1 is working:

CodeSandbox demo: https://codesandbox.io/p/sandbox/quirky-gagarin-speccj?file=%2Fapp%2Fpage.tsx

Screenshot 2023-03-12 at 11 22 30

Will do! πŸ‘

cc @JesseKoldewijn, in case this approach is accepted by the team and you want to get another PR in for Next.js!