Serving User-Generated SVG Safely on Isolated Domains

User-generated Scalable Vector Graphics (SVG) present severe security challenges because they are XML-based files capable of executing JavaScript, triggering cross-site scripting (XSS) attacks, and loading malicious external entities. Serving untrusted SVGs from an isolated domain separates user-uploaded files from your main application’s origin, protecting session tokens, cookies, and sensitive APIs from compromise. This article covers the essential architectural patterns, HTTP headers, sanitization steps, and rendering controls required to host user-uploaded SVGs securely.

Why User-Generated SVGs Are Risky

Unlike raster images (such as JPEG or PNG), SVGs are dynamic documents that support scripting and interactivity. An SVG file can contain:

Best Practices for Domain Isolation

Host all user-uploaded content on a completely distinct apex domain or a non-shared subdomain that does not share cookies with your primary domain.

2. Configure Strict Content Security Policy (CSP)

When serving the SVG from the isolated domain, enforce a restrictive CSP header to prevent any script execution in the event a user opens the SVG link directly.

Content-Security-Policy: default-src 'none'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; sandbox

The sandbox directive disables script execution, form submissions, and popups within the SVG context.

3. Set Crucial HTTP Security Headers

Accompany every SVG response with security headers to enforce the correct content type and prevent MIME-sniffing:

File Processing and Sanitization

Server-Side Sanitization

Never store or serve raw user-submitted SVG files without cleaning them first:

  1. Parse with a Hardened XML Parser: Disable DTD parsing, external entity resolution (XXE prevention), and XInclude processing.
  2. Strip Executable Nodes: Remove all <script>, <foreignObject>, <iframe>, and <object> elements.
  3. Sanitize Attributes: Strip all event handlers (onload, onclick, onerror, etc.) and ensure href or xlink:href attributes only use safe protocols (http, https, or relative paths), explicitly blocking javascript: or data: URIs.
  4. Use Dedicated Libraries: Use battle-tested tools such as DOMPurify (configured specifically for SVG/XML) or SVG-specific sanitizers in your backend language.

Optional Raster Conversion

If full vector scalability is not strictly required by your application (for example, profile pictures or document previews), convert uploaded SVGs into static raster formats like WebP or PNG on upload. This eliminates the vector attack surface entirely.

Safe Rendering in the Client Application

How your main application displays the SVG matters just as much as where it is hosted: