XSS prevention stops bad code from running in your app. It keeps users safe from attacks that steal data or break your site.
0
0
XSS prevention in templates in Vue
Introduction
When showing user comments or messages on your website
When displaying data from external sources like APIs
When accepting and showing user input in forms
When rendering dynamic content that might include HTML
When building any public-facing web page with user content
Syntax
Vue
<template>
<div>{{ userInput }}</div>
</template>Vue automatically escapes content inside double curly braces {{ }}.
Use v-html only if you trust the content, because it inserts raw HTML.
Examples
Vue shows the script tags as text, not as code to run. This prevents XSS.
Vue
<template>
<p>{{ message }}</p>
</template>
<script setup>
const message = '<script>alert("XSS")</script>'
</script>Using
v-html inserts HTML directly. Only do this with safe content.Vue
<template> <p v-html="trustedHtml"></p> </template> <script setup> const trustedHtml = '<strong>Safe bold text</strong>' </script>
Sample Program
This example shows how Vue escapes the comment inside {{ }} so the script does not run. But using v-html inserts the raw HTML, which can run harmful code.
Vue
<template>
<div>
<h2>User Comment:</h2>
<p>{{ userComment }}</p>
<h2>Unsafe HTML with v-html (dangerous):</h2>
<p v-html="userComment"></p>
</div>
</template>
<script setup>
import { ref } from 'vue'
const userComment = ref('<img src=x onerror=alert("XSS Attack")>')
</script>OutputSuccess
Important Notes
Always prefer using {{ }} for user content to keep it safe.
Only use v-html with content you fully trust or have sanitized.
Consider using libraries to clean HTML if you must display user HTML safely.
Summary
Vue escapes content inside {{ }} to prevent XSS automatically.
Using v-html inserts raw HTML and can cause XSS if content is unsafe.
Always validate or sanitize user input before showing it as HTML.