Qwerkly
Contact Us

Using dangerouslySetInnerHTML Safely in Next.js

Nate S.
3/18/2025

Using dangerouslySetInnerHTML Safely in Next.js with isomorphic-dompurify

When building web apps with Next.js, you might encounter situations where you need to render raw HTML inside a React component. This often happens with user-generated content or third-party embeds. React’s dangerouslySetInnerHTML enables this, but as the name warns, it can introduce serious security risks if used improperly.

Why is dangerouslySetInnerHTML Dangerous?

React escapes content by default to protect against cross-site scripting (XSS) attacks. However, when you use dangerouslySetInnerHTML, you bypass this protection by inserting raw HTML into the DOM. This means if your content is not properly sanitized, malicious scripts can run.

For example:

jsx
const UnsafeComponent = ({ content }) => (
<div dangerouslySetInnerHTML={{ __html: content }} />
);

If content contains:

html
<script>alert('Hacked!');</script>

The script will execute, potentially compromising your site and users.

How to Use dangerouslySetInnerHTML Safely with isomorphic-dompurify

The key to safely rendering raw HTML in Next.js is to sanitize the content first. One of the best tools for this is isomorphic-dompurify — a library that works both on the client and server side, perfect for Next.js’s isomorphic rendering.

Step 1: Install isomorphic-dompurify

Using npm:

bash
npm install isomorphic-dompurify

Or yarn:

bash
yarn add isomorphic-dompurify

Step 2: Sanitize HTML Before Rendering

Import the library and sanitize your content before passing it to dangerouslySetInnerHTML:

jsx
import DOMPurify from 'isomorphic-dompurify';

const SafeComponent = ({ content }) => {
const cleanHTML = DOMPurify.sanitize(content);

return <div dangerouslySetInnerHTML={{ __html: cleanHTML }} />;
};

This ensures any malicious scripts or unsafe markup are stripped out, keeping your app secure.

Why isomorphic-dompurify?

Unlike dompurify, which works only in the browser, isomorphic-dompurify supports both server and client environments. This makes it ideal for Next.js projects where rendering happens on the server during initial load.

Additional Next.js Security Tips

Sanitizing HTML is crucial but consider these extra measures:

  • Avoid inline event handlers like onclick in your HTML content.

  • Implement a strict Content Security Policy (CSP) to reduce XSS risks further.

  • Validate and sanitize input on the backend as well as frontend.

  • Keep your dependencies up to date, especially security-related packages like isomorphic-dompurify.

Learn More About Next.js Security

For comprehensive Next.js security best practices, check out the official Next.js Security documentation.

At Qwerkly, we emphasize secure, scalable web development. If you want help building safe and performant Next.js apps, contact our team for expert guidance.