0
0
Vueframework~8 mins

XSS prevention in templates in Vue - Performance & Optimization

Choose your learning style9 modes available
Performance: XSS prevention in templates
HIGH IMPACT
This affects page security and rendering speed by controlling how user input is handled and displayed in templates.
Displaying user-generated content safely in Vue templates
Vue
<template>
  <div>{{ userInput }}</div>
</template>
<script setup>
const userInput = '<img src=x onerror=alert(1)>'
</script>
Vue automatically escapes HTML in mustache syntax, preventing script execution and avoiding layout shifts.
📈 Performance GainNo extra reflows or layout shifts caused by injected scripts; safer and more stable rendering.
Displaying user-generated content safely in Vue templates
Vue
<template>
  <div v-html="userInput"></div>
</template>
<script setup>
const userInput = '<img src=x onerror=alert(1)>'
</script>
Using v-html directly with untrusted input allows malicious scripts to run, causing security risks and potential layout shifts.
📉 Performance CostTriggers layout shifts (CLS) and can block interaction (INP) if scripts execute unexpectedly.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Using v-html with untrusted inputAdds nodes dynamicallyTriggers multiple reflows if scripts modify layoutHigh due to repaints and possible script execution[X] Bad
Using {{ }} interpolation for user inputNo extra nodes, text onlyNo reflows caused by script injectionLow paint cost, stable layout[OK] Good
Rendering Pipeline
Vue escapes user input during template compilation, so the browser renders text safely without executing scripts. This avoids extra layout recalculations caused by dynamic HTML injection.
Template Compilation
Style Calculation
Layout
Paint
⚠️ BottleneckLayout and Paint stages can be expensive if malicious HTML causes reflows or repaints.
Core Web Vital Affected
INP
This affects page security and rendering speed by controlling how user input is handled and displayed in templates.
Optimization Tips
1Always use {{ }} interpolation for user content to prevent XSS.
2Avoid v-html with untrusted data to prevent layout shifts and script execution.
3Check DevTools for unexpected DOM changes and layout shifts after rendering user input.
Performance Quiz - 3 Questions
Test your performance knowledge
Which Vue template syntax prevents XSS by escaping user input?
ADirectly setting innerHTML in mounted hook
BUsing {{ userInput }} interpolation
CUsing v-html directive with userInput
DUsing raw HTML strings in template
DevTools: Elements and Performance panels
How to check: Inspect the DOM in Elements panel to see if user input is rendered as text or HTML. Use Performance panel to record and check for layout shifts or long tasks caused by script execution.
What to look for: Look for unexpected DOM nodes or layout shifts in the flame chart indicating unsafe HTML rendering.