How do you use an SVG as background image without affecting security?

twitter logo github logo ・1 min read

I want to use an SVG as a backround image for one of my pages. For this, I have to make my CSP img-src rule as img-src 'self' data:
However, this will be an unsafe choice as explained here.

Has anyone faced this issue? If yes, how did you overcome it?

twitter logo DISCUSS (10)
markdown guide

Don't use a base64'd version of the image, or anything using the data protocol.

You can use an url towards the image instead, which will make it safe.


I had tried with a relative url previously and the request was going for the base64'd version. It works only if I use the full URL. I didn't want to hardcode the URL.
Anyways, thanks!


what was your CSS? you should be using a URL not data:

This doesn't work:

.back-img {
    background-image: url("../img/bg.svg")

But this does:

.back-img {
    background-image: url("")

I just don't want to hardcode the URL

Try url('/img/bg.svg'), not sure if that will work though.

I don't see the difference between your snippet and mine πŸ˜….
I know my relative URL is right, because without CSP it works fine.

default-src 'none' ; script-src 'self'; style-src 'self'; img-src 'self' ; font-src; connect-src 'self'; media-src 'none' ; object-src 'none' ; child-src 'none' ; frame-src 'self'; worker-src 'self' ; frame-ancestors 'none' ; form-action 'none' ; upgrade-insecure-requests; block-all-mixed-content; base-uri 'self'; manifest-src 'self';

the difference between url('/img/bg.svg') and url("../img/bg.svg") is that the former is an absolute path and will always refer to the same resource the latter is a relative path and the resource it refers to will change depending on the URL of the page that makes the request.

For example if the page making the request is then '/img/bg.svg' will look for the SVG at whereas '../img/bg.svg' will look for the SVG at


Thanks for all who helped πŸ™‚.
I have found out the cause of my problem.
I had used vue-cli to build my project and it used a package called 'url-loader' which was inlining images as data urls whenever the size of the image was less than 1000 bytes. That's the reason why my relative URL was getting converted to data url. I have reduced that limit to 1 byte to avoid any conversion.

Classic DEV Post from Mar 29

Speed of Voice - The Pace of Your Presentation Can Heavily Impact How Well it Lands

Learn how to control the pace of your voice in your presentation to land your message

Drishit Mitra profile image
I am a curious developer who likes to code, eat and sleepπŸ˜‹.

Sore eyes? now has dark mode.

Go to the "misc" section of your settings and select night theme ❀️