vue.jsnuxt3.jsdompurify

How can DOMPurify be used in a Nuxt application to save cleaned input to Pinia store?


I have included DOMPurify in my Nuxt application as a plugin imported from a layer. I have a textarea that is capturing user input and I can use the v-dompurify-html directive to display the text cleaned by DOMPurify in the UI. I want to save that cleaned text to the Pinia store I'm using for state management (and eventually to an external database), but have been unable to do so.

Here are relevant parts of my application:

In the base layer /plugins directory, a dompurify.ts file containing:

import VueDOMPurifyHTML from "vue-dompurify-html";

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.vueApp.use(VueDOMPurifyHTML);
});

In my nuxt.config.ts file:

export default defineNuxtConfig({
  devtools: { enabled: true },
  modules: ['@pinia/nuxt', '@nuxt/eslint'],

  extends: ['../base-project'],
});

In my component:

<template>
  <div>
    <textarea
        v-model.trim="entry"
        maxlength="3000"
        @input="recordEntry"
      ></textarea>

    <p v-dompurify-html="entry"></p>
  </div>
</template>

<script setup>
const entry = defineModel({ type: String, default: "" });
const appStore = useMyStore(); // standard Pinia store

function recordEntry(event) {
  if (event.target.value !== "") {
    const sanitizedEntry = DOMPurify(event.target.value)
    // ^^^ This is not working

    appStore.setAppState(sanitizedEntry);
  }
}
</script>

The error in the browser console when entering text is "DOMPurify is not defined."


Solution

  • I was able to implement a solution based on this blog article: https://blog.hyperlink.fi/using-dompurify-in-nuxt3

    My dompurify.ts file matches that example. In my component, I added the const { $sanitizeHTML } = useNuxtApp(); line. I initially tried using just const sanitizedContent = $sanitizeHTML(entry.value);, but that did not take into account that entry is a ref(). So updated that to be:

    const sanitizedContent = computed(() => {
      return $sanitizeHTML(entry.value);
    });
    

    And I was able to use the sanitizedContent in my function to update the Pinia store.