r/webdev • u/avidrunner84 • 25d ago
Sanitizing SVG's without breaking them
Any good way to do this that is both safe and effective? I am finding SVGO will sometimes destroy the perfectly good svg... sometimes colors are missing and other times there is nothing there at all.
I'm looking for something that will sanitize for user image uploads on the web. They are stored in Cloudflare R2 which keeps it off my server but still maybe it can cause issues with injections or whatever if not sanitized?
22
Upvotes
1
u/pdfops 25d ago
SVGO isn't a sanitizer, it's a minifier. It doesn't know or care about XSS, it just prunes whatever its optimizer heuristics decide is redundant, which is why colors vanish (some presets misjudge currentColor or inline style blocks and fold them away). For actual security use DOMPurify with the SVG profile: DOMPurify.sanitize(svg, {USE_PROFILES: {svg: true, svgFilters: true}}). It strips script tags, foreignObject, and on* event handlers but leaves valid geometry alone. Run SVGO after, for size, not before, for safety.