How-To Guide

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

  1. Why SVGs Carry Both Security Risk and Byte Bloat
  2. Sanitizing Untrusted SVGs Before Optimization
  3. Encoding Compact UTF-8 CSS Data URIs
  4. CSP, Theme Tokens, and Browser Rendering Pitfalls
  5. Verifying Byte Savings, CSP Compliance, and XSS Safety

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+xml boundaries: When an SVG loads via <img src="data:..."> or CSS background-image: url(...), it executes in an isolated SVG image document with zero access to your page’s :root CSS custom properties (var(--color-accent)) or currentColor. Either bake explicit colors per variant or apply CSS mask-image: url(...) paired with background-color: currentColor for monochrome UI icons!
  • Strict Content Security Policy img-src: A strict CSP containing img-src 'self' blocks data:image/svg+xml images everywhere unless you explicitly allow img-src 'self' data: (while keeping script-src and object-src 'none' tightly locked).
  • Missing xmlns="http://www.w3.org/2000/svg": Inline <svg> inside HTML5 works without xmlns, so designers often copy markup from DevTools and paste it into a Data URI—only for browsers to reject the standalone XML document silently unless xmlns='http://www.w3.org/2000/svg' is present on the root element.
  • Deleting viewBox during aggressive minification: Stripping width/height is fine when styling via CSS, but deleting viewBox destroys responsive scaling inside <img> and background-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:

  1. Adversarial payloads containing onload=, javascript: links, or active script elements are stripped completely and throw or neutralize cleanly.
  2. Hex fill attributes (fill="#0ea5e9") convert cleanly to %230ea5e9 without fragment truncation.
  3. Missing xmlns="http://www.w3.org/2000/svg" is either injected automatically or rejected at build time.
  4. Production CSP headers allow img-src 'self' data: while maintaining object-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.

Related Examples

Interactive Tools for This Topic