0
0
Vueframework~30 mins

XSS prevention in templates in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
XSS Prevention in Vue Templates
📖 Scenario: You are building a simple Vue app that displays user comments on a webpage. Users can submit comments that might contain HTML or scripts. To keep the site safe, you need to prevent any harmful code from running by properly handling the comment content in the Vue template.
🎯 Goal: Build a Vue component that safely displays user comments by preventing XSS attacks using Vue's template syntax.
📋 What You'll Learn
Create a Vue component with a reactive list of comments.
Add a configuration variable to toggle raw HTML rendering.
Use Vue template syntax to safely display comments.
Add a final toggle to switch between safe text and raw HTML rendering.
💡 Why This Matters
🌍 Real World
Websites that display user-generated content must prevent harmful scripts from running. This project shows how Vue helps keep content safe by default.
💼 Career
Understanding XSS prevention is essential for frontend developers to build secure web apps and protect users from attacks.
Progress0 / 4 steps
1
Set up the comments data
Create a Vue component using <script setup> and define a reactive variable called comments as an array with these exact strings: 'Hello, world!', '<script>alert("XSS")</script>', and 'Nice to meet you!'.
Vue
Hint

Use ref from Vue to create a reactive array named comments with the exact strings.

2
Add a configuration variable to toggle raw HTML
Inside the <script setup>, add a reactive boolean variable called showRawHtml and set it to false. This will control whether comments render as plain text or raw HTML.
Vue
Hint

Use ref(false) to create showRawHtml as a reactive boolean.

3
Display comments safely using Vue template syntax
In the <template>, use a v-for loop with comment as the item to iterate over comments. Inside the loop, display each comment using double curly braces {{ comment }} to ensure safe text rendering.
Vue
Hint

Use v-for="(comment, index) in comments" and display with {{ comment }} inside a list item.

4
Add toggle to switch between safe text and raw HTML rendering
Modify the <template> so that inside the v-for loop, it conditionally renders the comment as raw HTML using v-html="comment" if showRawHtml is true, otherwise it shows safe text with {{ comment }}. Use v-if and v-else for this toggle.
Vue
Hint

Use v-if="showRawHtml" v-html="comment" and v-else with {{ comment }} inside the list item.