Optimizing and Inlining SVG Data URIs Safely
Strip dangerous SVG script elements and event handlers, minify path coordinates, and encode compact UTF-8 CSS data URIs without Base64 bloat.
On this page
Why SVGs Carry Both Security Risk and Byte Bloat
Scalable Vector Graphics (SVG) look like harmless image assets, yet under the hood an .svg file is full executable XML. Untrusted icons from third-party icon packs, partner logos, or user uploads frequently contain editor metadata, hidden comments, external tracking pixels, and active DOM hooks such as onload attributes, foreignObject HTML wrappers, or clickable javascript: links. Opening a malicious SVG directly in a browser tab executes JavaScript inside the hosting origin’s security context—making SVG uploads a textbook Stored XSS vector.
Even trusted icons exported directly from Figma or Illustrator arrive bloated with XML preambles, id="Layer_1", high-precision floating-point coordinates (14.0000003), and unnecessary xmlns:xlink declarations. Converting that bloated markup blindly with btoa() bloats your stylesheet another 33% while destroying gzip redundancy. You can sanitize, minify, preview, and compare UTF-8 versus Base64 byte footprints immediately in the Interactive SVG to Data URI Converter.
Sanitizing Untrusted SVGs Before Optimization
Treat every external SVG as untrusted input—never pass raw user SVG markup to innerHTML or serve uncleaned .svg files inline from your application origin. While browsers isolate scripts when rendered inside <img> or CSS background-image, an attacker or curious user can simply right-click “Open image in new tab” to execute scripts inside an unprotected .svg endpoint.
Even seemingly benign SVG attributes pose risks beyond obvious event handlers. An external use element referencing a remote SVG sprite (href="https://attacker.test/sprite.svg#icon"), an inline CSS block containing @import or url(...), or an active SVG animation tag manipulating href attributes at runtime can leak visitor IP addresses or bypass shallow string filters. First-party build pipelines and upload sanitizers should strip executable elements, external references, and risky URL schemes using an explicit allowlist parser (such as DOMPurify configured strictly for { USE_PROFILES: { svg: true, svgFilters: true } }) or a deterministic sanitizer pass before running minification.
In addition to security stripping, trim structural bloat introduced by design suites before encoding: remove data-name layer labels, empty <g> wrapper groups, hidden display="none" drafts, and excessive coordinate precision (rounding 12.3456789 down to two decimal places like 12.35 rarely alters visual fidelity on 24px icons while cutting path length in half).
const FORBIDDEN_ELEMENTS = new Set([
"script",
"foreignobject",
"iframe",
"object",
"embed",
"animate",
"set",
]);
export function sanitizeAndMinifySvg(rawSvg: string): string {
const trimmed = rawSvg.trim();
if (!/^<svg\b/i.test(trimmed)) {
throw new Error("Input must start with an <svg> root element");
}
// Strip XML declaration, DOCTYPE, and comments first
let cleaned = trimmed
.replace(/<\?xml[\s\S]*?\?>/gi, "")
.replace(/<!DOCTYPE[\s\S]*?>/gi, "")
.replace(/<!--[\s\S]*?-->/g, "");
// Reject or strip dangerous tags completely
for (const tag of FORBIDDEN_ELEMENTS) {
const pairRe = new RegExp(`<${tag}\\b[\\s\\S]*?<\\/${tag}>`, "gi");
const selfRe = new RegExp(`<${tag}\\b[^>]*\\/?>`, "gi");
cleaned = cleaned.replace(pairRe, "").replace(selfRe, "");
}
// Remove inline on* handlers and javascript:/data:href vectors
cleaned = cleaned
.replace(/\s+on[a-z]+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, "")
.replace(
/\s+(?:xlink:)?href\s*=\s*(?:"\s*(?:javascript|vbscript|data):[^"]*"|'\s*(?:javascript|vbscript|data):[^']*')/gi,
"",
);
// Collapse redundant whitespace between tags while keeping attribute spacing intact
return cleaned
.replace(/>\s+</g, "><")
.replace(/\s{2,}/g, " ")
.trim();
}
Notice that regex stripping shown above works cleanly for build-time static icon sanitizing and safety checks; for arbitrary untrusted user uploads on a server, pair regex defense with a full XML/HTML AST sanitizer (such as DOMPurify with jsdom or isomorphic-dompurify) and serve uploaded assets from a dedicated sandbox domain with Content-Security-Policy: sandbox; default-src 'none' and Content-Disposition: attachment if downloaded directly.
Encoding Compact UTF-8 CSS Data URIs
Once the SVG is clean and minified, avoid Base64 when embedding icons inside CSS url(...). As Taylor Hunt demonstrated in “Optimizing SVGs in data URIs”, a UTF-8 percent-encoded data URI wrapped in double quotes inside CSS url("...") preserves human-readable ASCII characters (d="M2 4..."), avoids the 33% Base64 expansion, and compresses aggressively with Brotli or gzip across multiple icons in the same stylesheet.
export function svgToCompactCssDataUri(cleanSvg: string): {
utf8CssUrl: string;
base64CssUrl: string;
savingsBytes: number;
} {
// Use single quotes inside the SVG markup so outer CSS url("...") needs no escaping
const singleQuoted = cleanSvg
.replace(/"/g, "'")
.replace(/[\r\n\t]+/g, " ")
.replace(/\s{2,}/g, " ")
.trim();
// Encode only characters that break CSS data URIs or URL fragments (#!)
const encoded = singleQuoted
.replace(/%/g, "%25")
.replace(/#/g, "%23")
.replace(/</g, "%3C")
.replace(/>/g, "%3E")
.replace(/&/g, "%26")
.replace(/\{/g, "%7B")
.replace(/\}/g, "%7D");
const utf8CssUrl = `url("data:image/svg+xml,${encoded}")`;
const base64 = Buffer.from(cleanSvg, "utf8").toString("base64");
const base64CssUrl = `url("data:image/svg+xml;base64,${base64}")`;
return {
utf8CssUrl,
base64CssUrl,
savingsBytes: base64CssUrl.length - utf8CssUrl.length,
};
}
Look closely at % and #: you must encode % as %25 first before encoding # as %23—otherwise #fff becomes %23fff and then gets double-encoded into %2523fff, breaking the fill color silently! Even more critically, forgetting to encode raw # inside fill='#38bdf8' truncates the data URI right at the hash fragment, causing browsers to receive malformed XML (...fill=') and render a blank box!
CSP, Theme Tokens, and Browser Rendering Pitfalls
Watch out for four subtle failure modes when embedding SVG data URIs in production stylesheets:
- CSS variables do not cross
data:image/svg+xmlboundaries: When an SVG loads via<img src="data:...">or CSSbackground-image: url(...), it executes in an isolated SVG image document with zero access to your page’s:rootCSS custom properties (var(--color-accent)) orcurrentColor. Either bake explicit colors per variant or apply CSSmask-image: url(...)paired withbackground-color: currentColorfor monochrome UI icons! - Strict Content Security Policy
img-src: A strict CSP containingimg-src 'self'blocksdata:image/svg+xmlimages everywhere unless you explicitly allowimg-src 'self' data:(while keepingscript-srcandobject-src 'none'tightly locked). - Missing
xmlns="http://www.w3.org/2000/svg": Inline<svg>inside HTML5 works withoutxmlns, so designers often copy markup from DevTools and paste it into a Data URI—only for browsers to reject the standalone XML document silently unlessxmlns='http://www.w3.org/2000/svg'is present on the root element. - Deleting
viewBoxduring aggressive minification: Strippingwidth/heightis fine when styling via CSS, but deletingviewBoxdestroys responsive scaling inside<img>andbackground-size: contain.
Verifying Byte Savings, CSP Compliance, and XSS Safety
Before committing inlined icons or SVG sanitization pipelines, run your SVG through the Interactive SVG to Data URI Converter to confirm the UTF-8 data URI renders visibly in the live <img> box and shrinks size compared to Base64. Also benchmark when to stop inlining: embedding five small 400-byte UI icons as UTF-8 data URIs eliminates five HTTP round trips at minimal CSS cost, whereas inlining a 25KB hero illustration bloats every page’s render-blocking stylesheet and loses separate browser caching across routes. In automated tests, verify four invariants:
- Adversarial payloads containing
onload=,javascript:links, or active script elements are stripped completely and throw or neutralize cleanly. - Hex fill attributes (
fill="#0ea5e9") convert cleanly to%230ea5e9without fragment truncation. - Missing
xmlns="http://www.w3.org/2000/svg"is either injected automatically or rejected at build time. - Production CSP headers allow
img-src 'self' data:while maintainingobject-src 'none'and reporting zero console violations on pages displaying the icons.
FAQ
- Can an SVG file really execute JavaScript in a user's browser?
- Yes. SVG is an XML document format that supports embedded scripting and inline event attributes. If a user navigates directly to an uploaded SVG on your primary domain or loads it via object/iframe, scripts run with your origin's cookies and DOM access.
- Why is UTF-8 percent-encoding smaller than Base64 for CSS SVG data URIs?
- Base64 turns every 3 bytes into 4 ASCII characters, adding a fixed 33 percent overhead and breaking gzip pattern matching. Keeping ASCII SVG markup readable with minimal percent-encoding (%23 for #, %3C for <) shrinks CSS bundles and compresses far better.
- Does loading an SVG inside an <img> tag or CSS background-image run its scripts?
- Modern browsers block script execution and external network requests inside SVGs loaded via <img> or CSS url(). However, sanitizing SVGs at build or upload time remains mandatory because users can open image URLs directly in a new tab.
Interactive Tools for This Topic
Report a problem with this articleOpens a pre-filled issue on GitHub.