How to Sanitize HTML Output from the Storyblok Rich Text Field

Storyblok is the first headless CMS that works for developers & marketers alike.

The @storyblok/richtext package converts rich text content into HTML strings, which it then renders into the DOM. This custom resolver generates HTML output that includes any raw content defined in the Storyblok Richtext field, which, in turn, may contain potentially unsafe code.

hint:

You only need to handle sanitization yourself if you use @storyblok/richtext with @storyblok/js, Storyblok's JavaScript SDK. All other frameworks SDKs handle sanitization for you.

Sanitization is critical

Injecting unsanitized HTML into a website can expose visitors to cross-site scripting (XSS) attacks. These allow attackers to execute malicious scripts that may lead to data theft, session hijacking, and other security breaches.

Since the @storyblok/richtext package doesn't sanitize the HTML output, it's your responsibility to ensure a safe web experience for users.

How to sanitize HTML?

One way to sanitize HTML output is with a third-party sanitizer library like sanitize-html, which helps clean up HTML fragments generated by rich text editors.

After you install sanitize-html, you can specify the permitted HTML tags and attributes, and clean the output before rendering it with the richTextResolver's render function.

The following snippet is an example of how to handle visual assets pulled from the Storyblok editor before injecting the content into the DOM:

import sanitizeHtml from 'sanitize-html';
import { richTextResolver } from '@storyblok/richtext';

const html = richTextResolver().render(yourRichTextContent);
const sanitizedHTML = sanitizeHtml(html, {
  allowedTags: sanitizeHtml.defaults.allowedTags.concat(['img', 'figure', 'figcaption']),
  allowedAttributes: {
    ...sanitizeHtml.defaults.allowedAttributes,
    img: ['src', 'alt', 'title']
  }
});

document.getElementById('your-element-id').innerHTML = sanitizedHTML;

To learn more about how sanitize-html helps you safeguard your users, visit the official documentation.