QA
Beginner LevelVue JS

Why is v-html dangerous and how do you sanitize raw HTML strings before rendering?

❓ Interview Prompt: Explain raw HTML rendering with v-html, Cross-Site Scripting (XSS) risks, and DOMPurify sanitization.

The 'v-html' directive renders raw HTML strings directly into a template element's 'innerHTML'.

XSS Vulnerability Risk:

Dynamically rendering unsanitized user-submitted HTML via 'v-html' allows attackers to execute malicious JavaScript scripts (Cross-Site Scripting / XSS) in victim browsers ('<img src="x" onerror="stealCookies()">').

Defense:

Always sanitize raw HTML strings using a trusted sanitization library like DOMPurify before passing them to 'v-html'!

Code Implementation Example

html
<script setup>
import { computed } from 'vue';
import DOMPurify from 'dompurify';

const userUntrustedHtml = '<p>Safe Text</p><script>alert("XSS Attack!")</script>';

// Sanitize HTML string before rendering!
const sanitizedHtml = computed(() => DOMPurify.sanitize(userUntrustedHtml));
</script>

<template>
  <!-- Render sanitized HTML safely -->
  <div v-html="sanitizedHtml"></div>
</template>
💡Sanitizing raw user HTML using DOMPurify before rendering with v-html.
🎯 Interview Key Takeaway

Never render raw untrusted HTML with v-html without first sanitizing it using DOMPurify to defeat XSS attacks.

#v-html#XSS#Security#Beginner
Back to all Vue JS Questions→

More Vue JS Interview Questions

Beginner LevelVue JS

What is the difference between Options API and Composition API in Vue 3?

Beginner LevelVue JS

What is the difference between ref() and reactive() in Vue 3?

Beginner LevelVue JS

What is the difference between computed properties, methods, and watch/watchEffect?