Best Tools to Sanitize SVG Files for the Web
Scalable Vector Graphics (SVGs) are widely used for crisp web graphics, but because they are XML-based documents, they can harbor malicious JavaScript, CSS, and external entities that cause Cross-Site Scripting (XSS) vulnerabilities. This article explores the primary security risks of unsanitized SVGs and details the most effective libraries and tools available across different programming ecosystems to sanitize SVG files securely before rendering them in the browser.
Why SVG Sanitization is Critical
Unlike raster formats like PNG or JPEG, SVGs can execute code. An
unsanitized SVG file can contain: * <script> tags
executing arbitrary JavaScript. * Inline event handlers such as
onload, onerror, or onclick. *
Malicious <foreignObject> tags embedding HTML iframes
or forms. * XML External Entity (XXE) attacks or Billion Laughs
denial-of-service payloads.
To safely display user-uploaded or third-party SVGs, you must sanitize them using trusted, allowlist-based libraries.
Top JavaScript and Client-Side Sanitizers
1. DOMPurify
DOMPurify is the standard for client-side and Node.js DOM sanitization. It is extremely fast, actively maintained, and specifically engineered to prevent XSS.
Key Features: Uses the browser’s native DOM parser, supports custom allowlists, and has built-in profiles for SVG.
Usage Example:
import DOMPurify from 'dompurify'; const cleanSvg = DOMPurify.sanitize(dirtySvg, { USE_PROFILES: { svg: true, svgFilters: true } });
2. sanitize-html
sanitize-html is a versatile HTML/XML sanitizer for Node.js environments.
- Key Features: Allows strict configuration of allowed tags, attributes, and URL schemes.
- Best Use Case: Server-side JavaScript applications where you need fine-grained control over accepted SVG elements.
Server-Side Sanitization Libraries
Sanitizing files on the server before storing them protects downstream users and prevents malicious files from entering your storage pipelines.
PHP: enshrined/svg-sanitize
svg-sanitize is the most popular PHP library designed specifically for cleaning SVG content, commonly used within CMS ecosystems like WordPress and Drupal.
Key Features: Cleans XML trees, removes potentially dangerous tags/attributes, and preserves safe vector paths.
Usage Example:
use enshrined\svgSanitize\Sanitizer; $sanitizer = new Sanitizer(); $cleanSvg = $sanitizer->sanitize($dirtySvg);
Python: defusedxml and nh3
Python applications handling SVGs should address both XML parsing vulnerabilities and XSS.
- defusedxml: Replaces standard Python XML parsers to defend against XML entity expansion attacks (XXE, entity bombs).
- nh3: Fast Python bindings to the Rust
ammonialibrary, capable of stripping unwanted scripts, attributes, and tags from SVG/HTML strings.
Go: bluemonday
bluemonday is a fast, robust HTML/SVG sanitizer for Go applications.
- Key Features: Provides policy-based sanitation to strip out executable scripts and dangerous attributes while preserving safe SVG presentation tags.
Build Tools and Optimizers
SVGO (SVG Optimizer)
SVGO is a Node.js-based tool for optimizing SVG vector graphics files.
- Security Role: While primarily an optimizer rather
than a dedicated security sanitizer, SVGO removes metadata, scripts,
hidden elements, and unused attributes when properly configured with
plugins like
removeScriptsandremoveUnknownsAndDefaults. - Recommendation: SVGO should be paired with a dedicated sanitizer (like DOMPurify) rather than used alone as a security boundary.
Best Practices for Safe SVG Web Rendering
- Use
<img>Tags Over Inline SVGs: Rendering an SVG via an<img>tag or CSSbackground-imageprevents scripts from executing in standard browsers. Reserve inline SVG (<svg>) only for cases requiring dynamic CSS manipulation or interaction. - Apply a Strict Content Security Policy (CSP): Set headers that restrict script execution and limit external connections within image contexts.
- Serve with Safe Content-Type Headers: Ensure files
served directly have the
Content-Type: image/svg+xmlheader and include theContent-Disposition: attachmentheader if the file is intended strictly for download rather than display.