SVG security
Why SVG can carry script, how img, inline, object and iframe differ, and how to handle uploads with sanitizing, separate origins, CSP and sandboxing.
An SVG file is an XML document, and the SVG language includes a <script> element. That makes an SVG from an untrusted source different from a PNG or JPEG: it is closer to a small web page than to a bitmap. This guide is about defending against that. It matters most if you accept uploads or inline SVG from other people.
Why SVG can carry script
MDN describes the SVG <script> element as the counterpart of the HTML one: it adds scripts to an SVG document, either inline or through href. SVG also allows event attributes. SVGO’s removeScripts plugin, for example, deletes <script> elements and strips event attributes such as onload and onclick.
This is a harmless illustration of the concept. When this file is opened as a document, the script runs with that document’s privileges:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10">
<circle cx="5" cy="5" r="4"/>
<script>console.log("this ran");</script>
</svg>
The risk is that an attacker’s script would run in your site’s origin and could act as the logged-in user. Whether it runs depends on how the file is loaded.
How embedding methods differ
MDN’s page on SVG as an image says that when an SVG is used through <img>, CSS background-image, list-style-image, content, the SVG <image> element or canvas drawImage, then JavaScript is disabled and external resources cannot be loaded unless inlined as data: URLs. MDN also says those restrictions do not apply when SVG is embedded as a document through <object>, <embed> or <iframe>, or when the file is opened directly.
The SVG 2 specification explains this with processing modes. An SVG in img should run in a secure mode with no scripts and no external references. Inline SVG, and SVG inside foreignObject, inherits the mode of the host document, so inline SVG is part of your page.
In short:
<img>and CSS images: safest for untrusted files. Scripts are off. The trade-off is no interactivity and no external resources.- Inline
<svg>: the markup becomes part of your DOM. Anything in it, including scripts and event attributes, is treated like your own page content. Only inline SVG you trust or have sanitized. <object>,<embed>,<iframe>: the file loads as its own document. Scripts can run. Without further controls, if the file is served from your site’s origin, they run as your origin.- Direct navigation: if a user is sent straight to the file’s URL, it is a document too.
The last point is the one that catches teams out. Putting uploads behind <img> tags in your own pages is not enough, because anyone can open the upload URL directly.
Sanitize uploads
OWASP defines untrusted data as anything your application did not create itself, and says every place it enters needs protection. For HTML-like markup, including SVG, it recommends a maintained sanitizer, and names DOMPurify. It also says to keep sanitizer libraries patched and not to modify content after sanitizing.
DOMPurify’s README says it supports HTML5, SVG and MathML. To allow only SVG and SVG filters, use the svg and svgFilters profiles. On a server it needs a DOM; the README recommends jsdom, kept current:
import createDOMPurify from 'dompurify';
import { JSDOM } from 'jsdom';
const window = new JSDOM('').window;
const DOMPurify = createDOMPurify(window);
const clean = DOMPurify.sanitize(uploadedSvgText, {
USE_PROFILES: { svg: true, svgFilters: true },
});
Notes from the README worth keeping:
- Do not combine
USE_PROFILESwithALLOWED_TAGSorALLOWED_ATTR;USE_PROFILESoverrides them. - Use a current jsdom. The README says older versions can enable XSS even when DOMPurify works correctly, and that happy-dom is not recommended.
- Leave
SAFE_FOR_XMLat its default unless you only handle HTML. The README warns against disabling it for SVG or MathML. - Do not edit the sanitized string afterwards.
Sanitizing removes content, so compare input and output on real files. A sanitizer can strip things you wanted to keep, and an SVG that relied on script will stop working. Store the sanitized result, not the original upload. SVGO’s removeScripts is a quick extra step, but I would not make an optimizer your only defense.
OWASP also advises validating URL-bearing attributes and allowing only expected schemes. In SVG, that applies naturally to href on <a>, <use> and <image>. MDN adds that browsers may apply the same-origin policy to <use> and that loading data URIs through <use> is deprecated for security reasons.
Serve user files from a separate origin
The strongest control is to ensure that even a malicious file has nothing to steal. MDN’s iframe page says sandboxing does not help if content can be opened outside the frame, such as in a new tab, and advises serving such content from a separate origin.
Use a different registrable domain, not just a subdomain you share cookies with, such as usercontent.example.net for uploads while the app runs on app.example.com. Do not set your session cookies on it. A script that runs there then has no access to the app’s cookies or storage. I would rate this above any filter.
Set response headers
For user-supplied files, send explicit headers:
Content-Type: image/svg+xml
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'; sandbox
Content-Disposition: attachment; filename="upload.svg"
What each does:
X-Content-Type-Options: nosnifftells the browser to trust the declaredContent-Typeinstead of guessing from the body. MDN notes this helps prevent XSS when user-uploaded content would otherwise be executed as HTML. Set a correct type too.Content-Security-Policyis defense in depth. MDN says a CSP is not an alternative to sanitizing input, and OWASP calls it an additional layer. Withdefault-srcorscript-srcset, inline scripts, inline event handlers andjavascript:URLs are blocked unless enabled. Thesandboxdirective applies an iframe-style sandbox to the resource it is served with. With no tokens, every restriction applies. Test the policy against your real files, because a strict policy can also block things they legitimately use.Content-Disposition: attachmentasks the browser to download the file rather than display it.inlineis the default and displays it. MDN’s page on this header does not itself discuss user-content risk, so treatattachmentas a common hardening practice, not a guarantee. It is useful where the file should never render in the browser. If you need the file to display in<img>, a download disposition is not the right fit; rely on the separate origin and sanitizing instead.
Sandbox iframes
If you must show an untrusted SVG as a document, put it in an iframe with the sandbox attribute:
<iframe sandbox src="https://usercontent.example.net/files/abc.svg"></iframe>
An empty sandbox applies all restrictions. MDN lists the effects: the content gets an opaque origin that fails the same-origin policy, cannot run scripts, submit forms, open popups, open modal dialogs, or navigate the top-level page. Each can be lifted with a token such as allow-scripts.
The trap is combining allow-scripts with allow-same-origin on same-origin content. MDN says it is strongly discouraged because the embedded document can remove its own sandbox attribute, making it no safer than no sandbox at all. If you need scripts, keep the content on a separate origin and leave allow-same-origin off.
Here is a plain SVG with no script, no event attributes and no external references. It uses only shapes and an internal reference, which is the kind of content you want your pipeline to leave intact:
A practical policy
- Prefer
<img>for any SVG that does not need interaction. See SVG vs PNG and JPG for when SVG is the right format. - Sanitize every upload on the server with a current DOMPurify and jsdom, and store the sanitized result.
- Serve uploads from a separate registrable domain with
nosniff, a restrictive CSP andsandbox. - Use
attachmentwhere the file should be downloaded, not displayed. - Inline only SVG you wrote or sanitized. Interactive features built with SVG and JavaScript belong in files you control.
- Keep the sanitizer and its DOM library updated, and review OWASP’s guidance when you change how files are rendered.
No single step is enough alone, because a sanitizer bug, a header mistake or a new embedding path can each fail.
Sources
Checked against these references on 2026-11-21.
- MDN: SVG as an image
- MDN: SVG script element
- W3C: SVG 2, conformance and processing modes
- OWASP: Cross Site Scripting Prevention Cheat Sheet
- DOMPurify (GitHub README)
- MDN: Content Security Policy (CSP)
- MDN: Content-Security-Policy sandbox directive
- MDN: Content-Disposition header
- MDN: iframe element and the sandbox attribute
- MDN: X-Content-Type-Options header
- MDN: SVG use element
- SVGO: removeScripts