Skip to content
Tutorials Center
My learning

Topics

Lesson 65 of 87 ยท Performance, Security and Ecosystem

Security in Vue

Learn how Vue protects you from XSS, where it cannot, and how to handle v-html, user URLs, styles and templates safely, with a runnable sanitizer demo.

A frontend framework sits between untrusted data and the page. Comments, usernames, search terms, URLs from the query string, and text from an API all end up in the DOM, and if any of them can become code, an attacker can run scripts in your visitors' browsers. That attack is called cross-site scripting (XSS), and it can steal sessions, read private data and act as the user.

Vue helps a lot: by default, it treats everything you render as text. The risks start when you step around that default. This lesson shows what Vue does for you, the few features that turn the protection off, and how to deal with user content, URLs, styles and templates safely. It also explains what Vue cannot do for you, because the real defense is spread across the browser, the server and your habits.

What Vue escapes for you

Text interpolation with {{ }} and normal attribute bindings do not parse their value as HTML. Vue sets the element's text (as textContent) or the attribute value, so a string like <b>hi</b> appears as visible characters instead of becoming bold text.

flowchart LR
  U["untrusted string"] --> I["mustache or :attr"]
  U --> H["v-html"]
  U --> S["sanitize first"]
  I --> T["shown as text<br/>safe"]
  H --> P["parsed as HTML<br/>dangerous"]
  S --> H2["v-html with clean markup"]
  H2 --> OK["only allowed tags remain"]

Interpolation is safe by default. v-html parses HTML, so the string must be trusted or sanitized first.

The demo compares the two. The comment contains an image tag with a broken source and an onerror handler. In a real attack that handler would send cookies or tokens to a server. Here it only replaces the image with a message, so you can see whether it ran.

Interpolation versus v-html

In the first box you read the raw tag as text. In the second box the browser built a real <img> element, the image failed to load, and the onerror code ran: the picture was replaced by "(attacker script ran)". The preview is sandboxed, so nothing harmful can happen here, but on your own site the same string would run with your page's full privileges. The rule is simple: never use v-html (or innerHTML, or a render function's innerHTML prop) with content a user can influence, unless it has been sanitized.

Sanitizing user content

Sometimes you do need user-authored markup: a blog comment with bold text and links, or HTML from a rich text editor. Two safe options exist.

  1. Do not accept HTML at all. Accept plain text or Markdown, and render it into a safe subset in a library that escapes by default. Often this is enough.
  2. Accept HTML, but run it through a sanitizer that keeps an allowlist of tags and attributes. In production, use a well-tested library such as DOMPurify, and sanitize on the server as well, since attackers do not need your frontend at all.

The key idea of a sanitizer is an allowlist: anything not listed is removed. A blocklist ("remove script tags") always misses something, because browsers accept many odd ways of running code: event attributes like onerror and onclick, javascript: URLs, SVG, and malformed markup that the parser fixes in surprising ways.

The next demo is a tiny sanitizer for teaching. It parses the HTML into an inert document (DOMParser does not run scripts or load images), walks the nodes, and rebuilds a fresh tree that contains only allowed tags, only allowed attributes and only safe link addresses. Do not paste it into a production app, since a real library covers far more edge cases.

A small allowlist sanitizer

Look at the sanitized source. The onclick and onerror attributes are gone, the <img> is dropped (it is not on the allowlist), the script is removed with its content, the javascript: link lost its href, and the good link kept its address but lost target (we did not allow it) and gained rel. Try adding your own attacks to the textarea, such as an SVG with onload, and see that anything not on the list disappears.

URLs and attribute bindings

Binding a value to an attribute is safe from HTML injection, but a URL attribute has another danger. A link such as <a :href="profileUrl"> runs JavaScript if the value is javascript:doBad(). Vue does not block this for you. The same holds for src on frames and for href on SVG anchors.

Check addresses from untrusted sources before binding them: parse them with new URL(...) and allow only the protocols you expect, as the sanitizer above does. Also check where a redirect parameter points before you navigate to it (for example ?next=https://evil.example), otherwise attackers can use your login page to send users elsewhere.

Checking user-supplied URLs

The parser lowercases the protocol, so the mixed-case attempt is caught too, and relative paths are accepted because they resolve against our own origin. Note the shape of the check: it lists what is allowed (http, https, mailto) rather than what is forbidden.

Style and CSS injection

Binding :style with a string or object that a user controls lets them change layout, hide buttons, overlay your page with a fake login form, or load images from their server through url() (a tracking and data-leak channel). Treat style values like any other input:

  • Let users choose from a fixed set (a theme name that maps to a class) instead of passing raw CSS.
  • If you allow a color, validate its format, for example with a pattern for #rrggbb, before binding it.
  • Never build a <style> element from user text, and never feed user input into v-bind() in CSS without validating it.

Never compile user input as a template

Vue templates are not data, they are code: they contain expressions and can call functions that are in scope. If you build a component with template: userString (or call compile() on text from users or from your database that users can edit), you give them a way to run JavaScript inside your app. This is called template injection.

JavaScript
// Dangerous: the user controls the template.
const Preview = { template: userSuppliedText };

// Safe: the user controls only data that is displayed as text.
const Preview = { props: ["text"], template: "<p>{{ text }}</p>" };

The same applies to server-side rendering: never place user text into the template source of an SSR app. If you want users to author a page, give them Markdown or a small, restricted format and render that yourself.

Also be careful with dynamic component names (<component :is="userValue"> should only pick from a map of known components), with v-bind="someObject" where the object comes from users (it can set any attribute, including ones you did not intend), and with libraries that render HTML from data (Markdown renderers must have raw HTML disabled or be passed through a sanitizer).

Defense beyond Vue

Vue's escaping is a first line of defense. A secure app also relies on:

  • Content Security Policy (CSP). A response header that tells the browser which scripts may run. A strict policy turns many XSS bugs into harmless errors. Note that the full build (with the template compiler) needs unsafe-eval in some setups, which is another reason to use precompiled SFCs.
  • Cookies with HttpOnly, Secure and SameSite. Script code cannot read an HttpOnly cookie, so a session cookie survives an XSS bug much better than a token in localStorage (more in Authentication Patterns).
  • Server-side validation and sanitizing. Anything coming from a browser can be forged. The frontend is only a convenience layer.
  • Updating dependencies. Run npm audit regularly and keep Vue and your libraries up to date.
  • Trusted sources only. Load scripts from your own origin or from a CDN with Subresource Integrity checks, not from addresses in user data.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens when you render the string <b>hi</b> with {{ text }}?

    Interpolation sets text content, so the markup is displayed literally. Only v-html (or innerHTML) parses it as HTML.
  2. 2. Which approach to sanitizing is the most reliable?

    An allowlist keeps only what you have decided is safe. Blocklists always miss some trick, such as event attributes or javascript: URLs.
  3. 3. Why is <a :href="userUrl"> still risky although Vue escapes attribute values?

    HTML escaping prevents breaking out of the attribute, but the value itself can be a URL with a dangerous protocol. Check the protocol before binding.
  4. 4. Which component definition is vulnerable to template injection?

    When the template string comes from users or user-editable data, their expressions run as code in your app. Data should be passed as props or state, never as the template.

Summary

  • Interpolation and attribute bindings treat values as text, which prevents most XSS by default.
  • v-html parses HTML: use it only for trusted content, or content sanitized with an allowlist sanitizer such as DOMPurify.
  • Validate URL protocols before binding user-supplied links, and check redirect targets.
  • Do not let users control raw CSS; offer fixed choices or validated values.
  • Never compile user input as a template: templates are code.
  • Combine Vue's defaults with CSP, secure cookies, server-side validation and up-to-date dependencies.

Next, in Authentication Patterns, you will see how login state, route guards and token storage fit together.