The One-Line CSP Header That Killed Our Page: default-src 'self' and Vite's Inline Images
Ops casually added a CSP response header, and the page died on the spot. Every frontend developer should know about this pitfall in advance.
A moment when the page suddenly went down
It happened on an ordinary workday. An ops colleague suddenly sent a message: "Your project's page won't open, take a look!" Followed by three exclamation marks.
My heart skipped a beat. The page was fine yesterday, no new release recently, not a line of code changed. How could it just go down? Could the server have been hijacked?
I opened the page and pressed F12. The console was red all over, more cheerful than the lanterns hung at Chinese New Year. Looking closely, the first errors were API failures: every API request the page depended on had failed, no data came back, and the whole page was white except for a skeleton screen spinning alone.
"Are the APIs down?" My first thought was a backend problem, so I asked ops to check service status. They checked and replied: the service is healthy, but there's no trace of any request in the logs.
That was strange. The frontend clearly sent requests, but the server never received them. Where did the requests go? Were they hijacked along the way?
I kept scrolling down the console with confusion, and something even weirder appeared: besides API errors, there were a pile of image loading failures. But these images were not ordinary static resources; they were small icons that Vite had inlined into the code during the build, usually invisible and unremarkable. Today they all died at once, not even leaving a full corpse behind.
APIs wouldn't send, inline images wouldn't load. These two things had nothing to do with each other, how could they both go on strike the same day? I stared at a strange phrase repeating in the console, Content-Security-Policy, and suddenly realized: there was probably an invisible 'hand' behind this, blocking all the page's resources at the door.
Full of questions, I opened the Nginx configuration file. Sure enough, among the dense configuration, I found a parameter that didn't exist yesterday:
add_header Content-Security-Policy "default-src 'self';";
That single line lay there silently, like a landmine buried at the page's entrance, exploding on whoever steps on it. What exactly is it, and how can it blow our page to pieces? Don't worry, we'll go through it slowly.
What is CSP anyway
This 'landmine' is formally called Content-Security-Policy (content security policy), abbreviated as CSP. According to MDN's explanation:
Content Security Policy (CSP) is a feature that helps prevent or reduce the risk of certain types of security threats. It consists of a series of directives sent from the website to the browser, requiring the browser to enforce restrictions on what code constituting the site is allowed to do.
In plain language: CSP is a 'whitelist' the server sets up for the browser. Which resources on the page can load and from where are all written on the list. The browser follows the list; anything not on it gets blocked.
Here's a key point: CSP is a rule the server sends to the browser through a response header, but it's the browser itself that does the actual blocking. This also explains the strange phenomenon during the earlier debugging: why were requests sent but no trace appeared in server logs? Because the requests never left the browser's door; they were detained by its own guard.
What does it protect against? Mainly XSS (cross-site scripting). Imagine an attacker injects a malicious script into the page through a vulnerability. Without CSP, the browser loads and executes it without hesitation. With CSP, the browser first checks the whitelist: is this script's source on the list? No? Sorry, refused. That way, even if the page is injected with malicious code, the damage can be greatly reduced.
Of course, CSP is not a panacea. Note MDN's wording is 'prevent or reduce', not 'eliminate'. It's more like installing a security checkpoint at the page's entrance; how strict the gate is depends on how the rules are written.
Besides response headers, CSP can also be set via a <meta> tag in HTML. However, the <meta> approach doesn't support all directives as completely as the response header, and maintaining it isn't as convenient as centralizing it in server config. So the response header method is generally recommended, and that's exactly what the ops colleague added this time.
What makes up a policy
CSP rules aren't complicated to write. A policy is a set of 'directive = source' pairs separated by semicolons:
directive-name allowed-source1 allowed-source2;
Let's dissect the line ops added: default-src 'self'; contains two key pieces of information. default-src is the directive name, telling the browser which type of resource this rule governs; 'self' is the source, telling the browser where that type of resource may be loaded from.
Think of CSP as a residential community's access control system: different types of deliveries (scripts, images, styles) go through different gates, and each gate has a list of who's allowed in. The common 'gates' (directives) are these:
| Directive | Resource type |
|---|---|
| default-src | Default channel for all resources (fallback) |
| script-src | JavaScript scripts |
| style-src | CSS styles |
| img-src | Images |
| font-src | Fonts |
| connect-src | API requests such as XHR, fetch, WebSocket |
| media-src | Audio, video |
| object-src | Plugin resources like <object> |
| frame-src | iframe frames |
| worker-src | Worker threads |
And the 'list' (sources) can be written in several ways. Common ones are:
| Source value | Meaning |
|---|---|
| 'self' | Only allow same-origin (protocol, domain, port all identical) |
| 'none' | Allow nothing, blanket ban |
| data: | Allow URLs starting with data: (e.g. base64 images) |
| blob: | Allow URLs starting with blob: |
| 'unsafe-inline' | Allow inline resources (inline scripts, inline styles) |
| https: | Allow any HTTPS source |
| Specific domain | e.g. https://cdn.example.com |
By now you can read the literal meaning of that line: 'All resources, by default, only allow same-origin.' Sounds nice, but why did our images and APIs still fail? The answer lies in default-src's 'fallback' temperament.
What exactly did default-src 'self' block
After the theory, let's return to the scene. First, listen to the browser's own 'confession'. In the console, the CSP rejection message looks like this:
Refused to load the image 'data:image/png;base64,iVBORw0KG...' because it violates the following Content Security Policy directive: "default-src 'self'". Note that 'img-src' was not explicitly set, so 'default-src' is used as a fallback.
This error carries a lot of information. Two key points: first, the blocked image URL starts with data:; second, the browser explicitly notes that img-src was not explicitly set, so default-src is used as a fallback.
The API errors follow the same formula: connect-src wasn't written, so default-src 'self' kicked in as the fallback, and the APIs are not same-origin with the page, so they were blocked. So what's this fallback all about? Let's talk in detail about default-src's temperament.
The 'fallback' temperament of default-src
The word fallback in the error is exactly how default-src works: it's the fallback. When the browser decides whether a resource can load, it first looks for a dedicated directive for that resource type: images look for img-src, APIs look for connect-src. If found, it follows that directive's list; default-src has no say. Only if not found does it consult default-src.
In other words, writing only default-src 'self' has roughly the same effect as writing all of these:
script-src 'self';
style-src 'self';
img-src 'self';
connect-src 'self';
font-src 'self';
……
Images, fonts, scripts, styles, API requests: all of them only accept 'same origin'. This also explains why all APIs failed: the API domain isn't same-origin with the page. The browser checks the list: connect-src not written separately? Then follow default-src's 'self', and the request is blocked instantly. The server naturally never sees a trace.
Conversely, once we write a dedicated directive for a resource type, it no longer listens to default-src. For example, after adding img-src 'self' data:;, image resources only follow img-src's list and have nothing more to do with default-src.
And if default-src isn't written at all? The answer is no protection at all: resources can load from anywhere. So while default-src governs broadly, it's also the last line of defense for the entire whitelist.
But note carefully: default-src's fallback is not for everything. Directives like frame-ancestors, base-uri, and form-action are not within its jurisdiction. If they aren't written, there's no protection; they never automatically inherit default-src's value. That's why they need to be written separately in the full config later.
Why some images fail after Vite bundling
For the image clue, we have to start with Vite's bundling mechanism. In our project, small icons and images are static files in the source. But Vite has a default behavior at build time: images smaller than a certain threshold are directly inlined as base64 strings, becoming URLs like data:image/png;base64,... embedded in the build output.
This behavior is controlled by Vite's assetsInlineLimit option, with a default value of 4096 bytes, i.e. 4KB. Images smaller than 4KB don't generate a separate file request after build; they're directly 'grown' into the code:
// In the build output
const img = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUg..."
This was meant as a kindness: small resources don't go through network requests, so the page loads faster. Who'd have thought this kindness would become a 'original sin' in front of CSP.
We've already seen the source table: data: is an independent scheme, completely different from 'self'. The browser sees data:image/png;base64,... and only considers it a data: URL; it doesn't care whether it originally came from an image file in the project. And because img-src wasn't written separately, it falls back to default-src 'self'; data: isn't on the whitelist, so the image is blocked.
Worth noting: larger images that weren't inlined still load from same-origin URLs like /assets/xxx.png after the build, and 'self' covers those completely. They weren't on the 'casualty list' of this incident. So precisely, what died were the small images inlined as data: URLs, not all images. That's why we saw some images still load.
Using the error to trace back the active policy
This debugging session also left us a reusable path. Next time you encounter CSP blocking, check in this order:
First, read the console error message. CSP rejection messages are very 'honest': the full URL of the blocked resource, the directive violated, and whether it used the default-src fallback are all written in black and white. Reading it carefully saves half the time.
Second, open the Network panel, find the page document (usually the first request), and check its response headers to confirm the actual active CSP content. This prevents cases where you think you changed the config but it didn't take effect, or where multiple config sources override each other.
Third, confirm the protocol and domain of the blocked resource URL: is it a same-origin path, a cross-origin URL, or a special scheme like data: or blob:? This determines which source rule governs it.
Fourth, map it to a directive: does this resource type have an explicit directive? Images check img-src, APIs check connect-src, scripts check script-src. None? Then default-src is the fallback.
After these four steps, the full picture of this incident came together: APIs were blocked via connect-src fallback, and inlined small images were blocked via img-src fallback. The culprit behind both 'cases' was that single line default-src 'self'.
With the blocked objects identified and the cause clear, only one question remained: how should this whitelist be reopened?
The fix: from one line to a full set
Once the culprit was found, the fix was clear: don't tear down the gate, but write a finer whitelist. Specify clearly for each resource type which channel it uses and which sources are allowed.
Together with ops, we changed that one line into this set:
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self'; media-src 'self' blob:; object-src 'none'; frame-src 'self'; frame-ancestors 'self'; worker-src 'self' blob:; manifest-src 'self'; base-uri 'self'; form-action 'self';" always;
The long string looks intimidating, but if you break it apart, it's just issuing 'passes' one by one by resource type. Save the config, reload Nginx, refresh the page: the inlined small images are back, the API data is back, and the console is finally no longer 'celebrating the New Year'.
Don't rush to copy this homework: this config was tailored to our project's resources, not a universal template to copy directly. For example, connect-src: if your APIs live on a separate domain, writing only 'self' isn't enough; you need to add the API domain to the whitelist:
connect-src 'self' https://api.example.com;
Below we go through the reasoning behind each directive, so you can configure your own project following the same thinking.
Why only open data: and blob: for specific resources
The core of this fix is naturally img-src 'self' data: blob:: issuing data: and blob: passes to the image channel, which immediately restores the inlined small images.
Similarly, font-src 'self' data: leaves an opening for inline fonts like iconfont; media-src 'self' blob: and worker-src 'self' blob: correspond to audio/video and Web Worker scenarios, kept according to the project's actual needs.
Some readers might ask: since we're afraid of blocking the wrong things, why not just add data:, blob:, and 'unsafe-inline' to every directive and be done with it?
Absolutely not. The value of a whitelist lies in 'least privilege'. Every source you allow is another window opened for attackers. Especially script-src, which is the main battlefield for XSS, must be strictest: only allow 'self', never grant 'unsafe-inline'. Once this script gate loosens, CSP becomes a dead letter.
The security trade-off of style-src 'unsafe-inline'
Sharp-eyed readers might notice a contradiction: we just said 'unsafe-inline' is unsafe, so why is it used brazenly for styles here?
It's a necessary compromise. Modern front-end projects, whether Vue's dynamic style binding :style or component libraries like Element Plus, write inline styles (style="...") to elements at runtime. If the style channel doesn't allow inline, the page loses its formatting on a large scale.
How big is the risk? 'unsafe-inline' opens up inline styles. Even if an attacker injects styles, they can only do limited things: alter the page's appearance or set up phishing camouflage. Compared to injecting scripts to steal data directly, the harm is an order of magnitude lower. Choosing the lesser of two evils, this risk is worth taking.
If you pursue extreme security, there are stricter options: use nonce (random number) or hash to precisely mark trusted inline styles. But they require the server to dynamically generate them on each response, which is a nontrivial refactoring cost, so most projects don't use them.
Remember this principle: never give ground on script-src, but style-src can compromise appropriately.
Nginx's always and config scope
Finally, let's talk about that unremarkable always at the end of the config. It's an old Nginx pitfall.
The add_header directive has a default behavior: it only applies to responses with status codes 200, 201, 204, 206, 301, 302, 303, 304, 307, and 308. That means without always, when the page returns error pages like 404 or 500, the CSP response header is 'absent from work'.
Don't underestimate error pages: they're also an XSS attack surface, for example by splicing malicious scripts into a 404 message. Adding always ensures every response wears this safety helmet.
There's another classic Nginx pitfall: add_header can be written at the http, server, and location levels, but if any add_header is written in a child level, all add_header directives from parent levels are not inherited. When debugging why a config doesn't take effect, first check if this rule is the culprit.
After changing the config, don't rush to celebrate. Use curl -I or the Network panel to inspect the actual response header and confirm it really took effect. Seeing is believing; the config file doesn't count.
Retrospective: if we could do it over
With the incident handled, let's look back: if we could do it over, how could we avoid this 'scare'?
First, take inventory before writing. Before applying CSP to a project, survey every resource the page loads: scripts, styles, images, fonts, APIs, iframes... What are their sources? Are there any data: or blob: URLs? Write the whitelist from that list, not by impulsively writing a single 'self'.
Second, observe before blocking. CSP provides a dedicated 'report only, don't block' response header: Content-Security-Policy-Report-Only. Usage is simple: just swap the header name:
add_header Content-Security-Policy-Report-Only "default-src 'self';" always;
With it in place, resources that violate the policy load normally and the page is unharmed. But the browser writes every record that 'would have been blocked' into the console as a warning starting with [Report Only]:
[Report Only] Refused to load the image 'data:image/png;base64,...' because it violates the following Content Security Policy directive: "default-src 'self'".
Run it like this for a while, fold each issue exposed by the reports into the whitelist, and once you're sure there's no collateral damage, switch the header back to the real Content-Security-Policy. If you want to collect violation reports on the server for centralized analysis, you can also add a report-uri directive to the policy, and the browser will automatically POST reports to the specified address.
Third, do regression verification after deployment. Open every key page, the login flow, and error pages, and have both frontend and ops confirm together. Security policy changes need testing just like code changes.
Ultimately, this incident can't really be blamed on the ops colleague. Adding a security header is a good thing, but security policy has never been only ops' business. Only frontend developers know exactly how the page loads resources; the whitelist is a list that both sides should confirm together.
Summary
Let's wrap up this 'horror story'.
The beginning was dramatic: ops added a parameter, and a chunk of the page went down. We started from those festive 'red lanterns' in the console, traced the errors to the Nginx config file, and finally dug up that line default-src 'self', a diligent guard holding the wrong list who, when strict, blocks even its own people.
Looking back, this incident was actually a gift. It forced us to understand three things:
First, CSP is a whitelist in the browser's hands: the server writes the list, the browser does the blocking. So when requests 'go out but the server never receives them', it's not unfair, they never left the house.
Second, default-src is the fallback clause. Before writing it, take an inventory of your assets: does the project have resources with a 'special identity' like data: or blob:? Small images inlined by Vite are the most common victims.
Third, a security policy is never 'set it and forget it'. Use Report-Only to observe first, tighten item by item, then do regression testing. Only traffic can prove whether the whitelist is correct.
Distill this debugging path into a mnemonic. Next time you encounter CSP blocking, follow it:
Read the console error → check the response header for hard evidence → identify the resource URL's scheme → map it to a directive via fallback → allow only the minimum scope → do regression testing after deployment.
Hey, wait: how did this post go from a troubleshooting story to a CSP syntax lesson, and end up resembling an Nginx config guide? Anyway, it doesn't matter. The highest level of debugging is turning the pit you stumbled into into a path others can avoid.
By the way, have you applied CSP in your project? Has this 'guard' ever injured you by mistake? Let's talk in the comments.
If you found this helpful, please follow my Juejin profile. For more articles, visit Xie Xiaofei's blog
Top 1 of 2 from juejin.cn, machine-translated. The original thread is authoritative.
This one hits home; I'd taken a fall into the default-src fallback issue before understanding it. Running Report-Only first and then tightening is a habit that can really save you.
[silly grin]