Updated November 14, 2026  ·  13 min read  ·  SVGVector

How to Sanitize SVG: An Allowlist Tested on 12 Payloads

A regex that strips <script> and on…= blocked 5 of the 12 payloads below and left 6 still live. An allowlist that parses the file as XML, walks the tree and keeps only known elements and attributes blocked all 11 that could be parsed — and on a real 890-byte Figma icon it cost 27 bytes and 0 of 14,400 pixels. That is the whole argument for doing it structurally, measured.

The other half of the argument is what you cannot see from the outside: after sanitising, ten of the eleven cleaned files rendered pixel-identical to the originals, and the one that changed changed because its artwork was a remote image the sanitiser removed. Nothing about the drawing was harmed; only the parts that reached outside the file.

Two rows of twelve cells comparing an allowlist sanitizer with a regex strip: the allowlist neutralises 11 of 12 payloads and refuses the twelfth as not-XML, while the regex leaves 6 executable or able to call out; on a real 890-byte icon the allowlist removes one attribute and changes no pixels.
Each cell is one payload after cleaning, put back into a page and re-tested in Chrome 157.0.8103.78. Red cells still executed or still requested a file from another origin.

Why stripping script tags is not sanitizing

The naive version is four lines, and it is worth writing out so the failure mode is concrete:

// The anti-pattern: a regex pass. Shorter output, not a safer file.
function naiveSanitize(src) {
  return src
    .replace(/<script[\s\S]*?<\/script>/gi, '')
    .replace(/\son\w+\s*=\s*("[^"]*"|'[^']*')/gi, '');
}

Run it over the twelve payloads and two of them still execute afterwards: the two whose attack is an <a href="javascript:">, one written plainly and one with the scheme encoded as &#106;avascript:. Four more still call out to the second origin, because the regex never looks at <image href>, at CSS @import, or at a <script href> that has no closing tag — the pattern requires </script>, and a self-closing element does not have one.

That is 6 of 12 still hostile after a pass that looks like it did something, because the output is shorter and the word script is gone. The failures are not exotic; they are the four ways an SVG reaches outside itself, none of which involves a script element.

Parse it as XML, not as HTML

The first line of a sanitiser decides most of its behaviour. DOMParser with image/svg+xml gives you a case-sensitive tree that matches the bytes in the file, and a parse error you can act on: if the file is not well-formed XML, refuse it rather than guessing. Parsing with innerHTML would give you the browser’s normalisation instead — which is exactly what an attacker wants, since that is where OnLoad becomes onload.

Everything downstream then works on one representation. Namespaced attributes arrive with their prefix stripped by localName, so xlink:href and href are the same key, and one rule covers both.

The allowlist

Three sets and one walk. Elements not in the set are removed with their subtree; attributes not in the set are removed individually; href gets a second check because a valid attribute name is not a valid value.

const SVG_NS = 'http://www.w3.org/2000/svg';

const OK_TAG = new Set([
  'svg', 'g', 'defs', 'symbol', 'use', 'a', 'title', 'desc', 'style',
  'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon',
  'text', 'tspan', 'textPath',
  'linearGradient', 'radialGradient', 'stop', 'pattern',
  'clipPath', 'mask', 'image',
  'filter', 'feGaussianBlur', 'feOffset', 'feBlend', 'feColorMatrix', 'feFlood',
  'feComposite', 'feMerge', 'feMergeNode',
]);

const OK_ATTR = new Set([
  'id', 'class', 'style', 'transform', 'viewBox', 'preserveAspectRatio', 'version',
  'x', 'y', 'x1', 'y1', 'x2', 'y2', 'cx', 'cy', 'r', 'rx', 'ry', 'width', 'height', 'd', 'points',
  'fill', 'fill-opacity', 'fill-rule', 'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin',
  'stroke-opacity', 'stroke-dasharray', 'opacity', 'clip-path', 'clip-rule', 'mask', 'filter',
  'gradientUnits', 'gradientTransform', 'spreadMethod', 'offset', 'stop-color', 'stop-opacity',
  'patternUnits', 'patternContentUnits', 'stdDeviation', 'in', 'in2', 'result', 'mode', 'type',
  'values', 'font-size', 'font-family', 'font-weight', 'letter-spacing', 'text-anchor',
  'dominant-baseline', 'role', 'aria-label', 'aria-hidden', 'focusable', 'href',
]);

// href: keep only local anchors, http(s) on <a>, and data: bitmaps on <image>
function hrefAllowed(el, raw) {
  const v = raw.replace(/[\u0000-\u0020]/g, '').toLowerCase();
  if (v.startsWith('#')) return true;
  if (el.localName === 'a') return /^https?:\/\//.test(v);
  if (el.localName === 'image') return /^data:image\/(png|jpe?g|gif|webp);base64,/.test(v);
  return false;
}

// Keep <style> (Figma puts every fill in .cls-1), but cut what can fetch: @import and remote url()
function sanitizeCSS(css) {
  let dropped = 0;
  const out = css
    .replace(/@import[^;{}]*;?/gi, () => { dropped++; return ''; })
    .replace(/url\(\s*(['"]?)([^)'"]*)\1\s*\)/gi, (m, q, u) => {
      const v = u.replace(/[\u0000-\u0020]/g, '').toLowerCase();
      if (v === '' || v.startsWith('#')) return m;
      dropped++;
      return 'none';
    })
    .replace(/(expression|javascript)\s*[:(]/gi, () => { dropped++; return 'none('; });
  return { css: out, dropped };
}

function sanitizeSVG(src) {
  const doc = new DOMParser().parseFromString(src, 'image/svg+xml');
  if (doc.querySelector('parsererror')) return { error: 'not XML' };
  const root = doc.documentElement;
  if (root.localName !== 'svg' || root.namespaceURI !== SVG_NS) return { error: 'not SVG' };

  const rejected = [];
  const removedAttrs = [];
  let cssDrops = 0;
  const all = [root, ...Array.from(root.querySelectorAll('*'))];

  for (const el of all) {
    if (el !== root && !OK_TAG.has(el.localName)) {
      rejected.push(el.localName);
      el.remove();
      continue;
    }
    for (const at of Array.from(el.attributes)) {
      const name = at.localName;                        // xlink:href -> href
      if (at.prefix === 'xmlns' || at.name.startsWith('xmlns')) continue;
      if (!OK_ATTR.has(name)) {
        removedAttrs.push(el.localName + '@' + at.name);
        el.removeAttributeNode(at);
        continue;
      }
      if (name === 'href' && !hrefAllowed(el, at.value)) {
        removedAttrs.push(el.localName + '@' + at.name);
        el.removeAttributeNode(at);
      }
    }
    if (el.localName === 'style') {
      const r = sanitizeCSS(el.textContent || '');
      cssDrops += r.dropped;
      el.textContent = r.css;
    } else if (el.hasAttribute('style')) {
      const r = sanitizeCSS(el.getAttribute('style'));
      cssDrops += r.dropped;
      el.setAttribute('style', r.css);
    }
  }

  return {
    svg: new XMLSerializer().serializeToString(root),
    removedNodes: rejected.length,
    removedAttrs: removedAttrs.length,
    cssDrops,
    rejected,
  };
}

Three details are load-bearing.

Remove against a snapshot, not a live list. querySelectorAll is collected once, before any deletion. Deleting a parent while iterating a live collection is the classic way to skip the next sibling — and the skipped node is the one that matters.

Compare localName, keep the namespace. An attacker can register their own prefix pointing at a different namespace; matching on the qualified name lets ev:onload through as a different attribute. localName collapses every prefix to one key, and the element check still looks at localName plus the SVG namespace on the root.

Refuse, do not repair, when the parse fails. One of the twelve payloads is a 376-byte file with a DTD declaring four nested entities. DOMParser returns a parser error, the function returns { error: 'not XML' }, and the caller shows nothing. Recovering from a parse error means guessing what the author meant, and the author is the problem.

Filtering href: the three cases that look safe

The href attribute is where an allowlist quietly becomes useless if you only check that the name is allowed. Three values that pass a naive check and should not:

What survives: #local-id on any element, http(s) on an <a> (a link the user chooses to follow is not an execution vector), and data:image/…;base64, on an <image>, because an embedded bitmap cannot reach the network. Everything else loses the attribute and keeps the element, so a stripped link still draws.

Keep the style block, filter what it can fetch

The tempting move is to delete <style> as well. Do that and every Figma export loses its colours: fills are written as .cls-1{fill:url(#g1)}, not as attributes, and a file with the style block removed renders as black shapes. So keep the element and filter the two constructs that reach the network — @import and any url() that is not a local fragment:

function sanitizeCSS(css) {
  let dropped = 0;
  const out = css
    .replace(/@import[^;{}]*;?/gi, () => { dropped++; return ''; })
    .replace(/url\(\s*(['"]?)([^)'"]*)\1\s*\)/gi, (m, q, u) => {
      const v = u.replace(/[\u0000-\u0020]/g, '').toLowerCase();
      if (v === '' || v.startsWith('#')) return m;   // url(#g1) is fine
      dropped++;
      return 'none';
    });
  return { css: out, dropped };
}

Measured on the CSS @import payload: the request that fired on every display before cleaning stops firing afterwards, and the file still renders its shapes. On the real icon, url(#g1) survives untouched, which is why the sanitiser’s output for that file is pixel-identical.

What the allowlist costs

On a normal export: 890 bytes in, 863 out — 27 bytes smaller, because one attribute was dropped. The attribute is data-name="icon/settings", a Figma layer label that no renderer uses. Elements removed: none. Pixels changed: 0 of 14,400.

The number that matters more is the one from the eleven payloads: after sanitising, ten rendered pixel-identical to the original, and the eleventh — the one whose artwork was a remote <image> — changed by 10,904 of 14,400 pixels, because removing the href removes the picture it pointed at. That is the correct outcome: the visible content of that file was the exfiltration.

A sanitiser that keeps everything and a sanitiser that keeps nothing both render safely. The cost of the allowlist is that some legitimate artwork features — filters, mesh gradients, a <switch>, animation elements — are not on the list and disappear. Extend OK_TAG for the features your own exports need; do not extend it because one file from the internet needed it.

Defence in depth: three settings that do not depend on your sanitiser

A parser bug or a missed attribute makes the whole check worthless, so the response headers carry the second half. All three were measured on the same payload in the threat-model article:

For an <iframe> that has to display a hostile file, add sandbox without allow-scripts — the frame gets a unique origin and script cannot run, which is the closest thing to <img> semantics with real interactivity removed.

Wiring it into an upload form

The order matters: size, then type, then parse, then sanitise, then store the sanitised bytes — never the original. If you keep the original around “for reference”, someone will serve it later.

// server side, Node — the browser-side sanitiser above runs first if you like,
// but the copy you serve has to be cleaned on the server too
app.post('/upload', async (req, res) => {{
  const raw = req.file.buffer.toString('utf8');
  if (req.file.size > 2 * 1024 * 1024) return res.status(413).end('too large');

  const result = sanitizeSVG(raw);              // same function as above
  if (result.error) return res.status(400).end(result.error);
  if (result.rejected.length) req.log.warn('stripped', result.rejected);

  await store(req.user.id, result.svg);         // store the cleaned string
  res.json({{ bytes: result.svg.length, removed: result.removedAttrs }});
}});

Two things that get skipped in a hurry. Reject anything larger than a few megabytes before parsing — a parser is the most expensive thing in this pipeline. And store the sanitised output as the canonical file, so every later code path — thumbnails, CDN copies, exports — inherits the cleaning rather than re-deciding it.

Frequently asked questions

Can I just use DOMPurify instead?

Yes, and for HTML you should. It handles SVG profiles too, and it is better tested than anything you will write this afternoon. The reason to read the allowlist above is to know what it is deciding on your behalf: which elements survive, which attributes go, and what happens to a url() inside a style block. Those decisions are the same ones, whether you write them or inherit them.

Does sanitising change how my icons look?

Measured on a real export: no. 890 bytes became 863, one metadata attribute was dropped, and 0 of 14,400 pixels changed. Files that change are the ones whose appearance depends on something the allowlist refuses — a remote image, a filter that is not on the list, an external <use>.

Where should the sanitiser run, browser or server?

Both, for different reasons. In the browser it gives instant feedback and blocks the obvious cases before upload. On the server it is the one that counts, because the copy you store and serve must be the cleaned one — a client-side check that the server does not repeat is a suggestion, not a control.

Is an SVG with no script still dangerous?

It can track. A remote <image href> or a CSS @import produced one request per display in every mode except <img>, which means a document thumbnail or an email graphic can report when it was opened. No code, no cookie access, but a signal.

Related SVG Workflows

Cleaning is one step. These cover the ones before and after it.

Check the file, then clean it

Validate the structure in the browser, edit the tree, and re-export without the parts that reach outside the document.

Try These Free Online Tools

No download required — convert, compress & optimize SVGs right in your browser

Validate

SVG Validator

Run this first: a file that will not parse as XML cannot be sanitised.

Open validator
Inspect

SVG Editor

Compare the tree before and after cleaning to see exactly what was removed.

Open editor
Optimise

SVG Optimiser

The size pass that runs after the security pass, not instead of it.

Open optimiser
Convert

SVG to Data URI

Encode a cleaned icon so it can be inlined without raw markup.

Encode it
Convert

SVG to Code

Turn the cleaned file into a component without the attributes you just stripped.

Convert to code
Render

SVG Crop / Flip / Rotate

Fix the viewBox on a file that came back from someone else.

Adjust the box