What’s the safest way to sanitize user-uploaded SVGs without breaking them?

0
0
Asked By QuietMango47 On

I'm accepting SVG files as user image uploads for a website. SVGO sometimes removes colors, breaks gradients or masks, or produces an empty image, so I'm looking for a safer approach that preserves the artwork while preventing scripts, event handlers, external references, or other injection risks. The files are stored in Cloudflare R2 rather than directly on my server, but I still want to make sure serving them cannot create security problems.

2 Answers

Answered By CopperCloud6 On

Inkscape’s cleanup options may produce files that happen to work, but Inkscape is not a security sanitizer. A parser-based sanitizer is a better choice for uploads. Also configure the hosting and response headers defensively: serve sanitized files with the correct image content type, avoid embedding untrusted SVG as inline HTML, and consider serving them from an isolated asset origin with a restrictive Content Security Policy. Keeping files in object storage reduces server exposure, but it does not make an unsafe SVG harmless when a browser renders it.

QuietMango47 -

That makes sense. I was treating storage outside the application server as if it removed the browser-side risk, so I’ll handle sanitization and serving policy separately.

Answered By PixelHarbor8 On

SVGO is primarily an optimizer, not a security sanitizer. It may remove attributes or IDs that the artwork still needs. Treat sanitizing and optimizing as separate steps: use a real SVG-aware sanitizer such as DOMPurify with its SVG profile to remove scripts, event handlers, external references, and risky elements like foreignObject. Only run SVGO afterward if you actually need optimization. If you do use it, be careful with options such as removeViewBox, cleanupIds or prefixIds, and removeUnknownsAndDefaults, since those can break scaling, gradients, masks, filters, and editor-generated SVGs.

Related Questions

Keep Your Screen Awake Tool

Favicon Generator

JWT Token Decoder and Viewer

Ethernet Signal Loss Calculator

Remove Duplicate Items From List

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.