next.js: Invalid HTML inside `dangerouslySetInnerHTML` breaks the page.

Bug report

Describe the bug

If invalid HTML is added to dangerouslySetInnerHTML, Next.js will output a blank page without providing any feedback. This can be hard to track when working with a CMS provider or markdown files.

To Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

  1. Clone https://github.com/lfades/nextjs-inner-html-bug
  2. Run yarn && yarn dev or npm i && npm run dev
  3. See that pages/index.js is a blank page with no errors

Expected behavior

Invalid HTML inside dangerouslySetInnerHTML should throw and/or let the user know that there’s something wrong.

The demo also has an index.html and index.js in the root directory that shows how the same code works in React alone, it doesn’t produce an error either, but it shows the content.

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 3
  • Comments: 23 (8 by maintainers)

Most upvoted comments

I’ll take this one on.

I tested this with app routes, and it works fine. The issue with the provided code from @Mbistami in the repo https://github.com/lfades/nextjs-inner-html-bug seems to be that it contains invalid style properties mixed into the HTML:

const HTML = <div> <h1>This is a title</h1> <style> <h2>This is a subtitle</h2> </div>

After removing the invalid <style> block, it works correctly in app routes.

I also had this problem when allowing user generated HTML. If you wrap the dangerously set HTML code using the sanitize package linked below - it auto-fixes this broken HTML problem for you.

https://www.npmjs.com/package/sanitize-html

<div dangerouslySetInnerHTML={{ __html: (sanitizeHtml(yourHtmlStringHere, {
   allowedTags: ['*'],
   allowedAttributes: {'*': [ '*' ]},
   allowedAttributes: { '*': ["*"]},
   allowedIframeHostnames: ['*']
   })) }} 
/>

I don’t have time to continue on this issue, so if anyone else wants to continue - feel free to do so!

My idea is to validate the HTML with perhaps html-validator package and logging the error to the console. I think adding something similiar to this in Main component could work:

export function Main() {
  const { inAmpMode, html, docComponentsRendered } = useContext(
    DocumentComponentContext
  )
+  const [invalidHtmlError, setInvalidHtmlError] = useState()

  docComponentsRendered.Main = true

+  useEffect(() => {
+    checkHtml()
+  })

+  const checkHtml = async () => {
+   try {
+      await htmlValidator(html)
+    } catch (error) {
+      setInvalidHtmlError(error)
+    }
+  }

  if (inAmpMode) return <>{AMP_RENDER_TARGET}</>

+  if (invalidHtmlError) {
+    Log.error(
+      "There's  an error with your HTML",
+      JSON.stringify(invalidHtmlError)
+    )
+  }

  return <div id="__next" dangerouslySetInnerHTML={{ __html: html }} />
}