Vue Sanitize Directive

0.2.1 · active · verified Sun Apr 19

vue-sanitize-directive is a Vue.js directive designed for declarative HTML sanitization within templates, powered by the flexible `sanitize-html` library. It provides a `v-sanitize` directive that can be used to remove potentially unsafe HTML content from user-provided input, offering various modifiers like `.strip`, `.basic`, `.inline`, and `.nothing` for different sanitization levels. The current stable version is 0.2.1. Recent updates in version 0.2.0 introduced support for both Vue 2.x and Vue 3.x, alongside experimental server-side rendering (SSR) capabilities. This package differentiates itself by integrating robust `sanitize-html` functionality directly into Vue's templating system, simplifying the process of displaying user-generated content safely. While convenient for client-side display, the documentation explicitly warns that primary validation and sanitization of user-provided input should always occur on the backend for robust security.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to install and globally register `vue-sanitize-directive` for a Vue 3 application. It showcases the default sanitization, `.strip` modifier, applying a custom allowlist, and the `.nothing` modifier, highlighting how the directive cleans potentially unsafe HTML content.

import { createApp } from 'vue';
import VueSanitize from 'vue-sanitize-directive';

const app = createApp({
  data() {
    return {
      unsafeHtml: '<p>Hello <script>alert("XSS")</script> World! <a href="javascript:alert(\'XSS\')">Click me</a> <span style="color: red;">Red Text</span></p>',
      anotherUnsafeHtml: '<div><img src="x" onerror="alert(\'XSS\')"></div>',
      customAllowedTags: ['p', 'span', 'strong']
    };
  },
  template: `
    <div>
      <h1>Vue Sanitize Directive Demo</h1>

      <h2>Default (.basic) Sanitization</h2>
      <p>Original: {{ unsafeHtml }}</p>
      <div v-sanitize="unsafeHtml"></div>
      <hr>

      <h2>.strip Modifier (removes all tags)</h2>
      <p>Original: {{ unsafeHtml }}</p>
      <div v-sanitize.strip="unsafeHtml"></div>
      <hr>

      <h2>Custom Allowlist (only p, span, strong)</h2>
      <p>Original: {{ unsafeHtml }}</p>
      <div v-sanitize="[customAllowedTags, unsafeHtml]"></div>
      <hr>

      <h2>.nothing Modifier (be careful!)</h2>
      <p>Original: {{ anotherUnsafeHtml }}</p>
      <div v-sanitize.nothing="anotherUnsafeHtml"></div>
    </div>
  `
});
app.use(VueSanitize);
app.mount('#app');

view raw JSON →