Sub topic 10
Content Security Policy and LWS
This chapter assumes you know Lightning web component structure, modern JavaScript with async/await, the same-origin policy, and how namespaces and static resources work in Salesforce. You should also have read the earlier chapters on namespace isolation, sandboxes and distortions, and third-party libraries.
Two separate layers of control
Lightning Web Security (LWS) and Content Security Policy (CSP) both restrict what your component code can do, but they work in different places.
- LWS runs inside the page's JavaScript engine. It wraps your namespace's code in a sandbox and distorts APIs such as
document,window, andElementmethods. It decides what your code can touch. - CSP is enforced by the browser itself. Salesforce sends a CSP header with the page, and the browser blocks any request, script, frame, or resource that violates it. It decides where your code can load things from and send data to.
A call has to pass both. If LWS lets fetch run but CSP does not list the target host, the browser blocks the request. If CSP allows a host but LWS distorts the API you used, the code still fails. Many "LWS errors" are really CSP violations, so the first diagnostic step is knowing which layer blocked you.
What Salesforce's CSP restricts
Salesforce sets CSP headers for Lightning Experience, Experience Cloud sites, and Visualforce. The policy limits the sources the page may use for each kind of content. The directives you meet most often are these:
| Directive | Controls | Typical component use |
|---|---|---|
| `script-src` | Where scripts can load from | `loadScript` with a static resource |
| `connect-src` | Targets for `fetch`, `XMLHttpRequest`, WebSocket, and similar connections | Calling an external REST API from the browser |
| `img-src` | Image sources | `<img src="https://cdn.example.com/logo.png">` |
| `style-src` | Stylesheet sources | `loadStyle` with a static resource |
| `font-src` | Font sources | Web fonts from a font provider |
| `frame-src` | Iframe sources | Embedding an external page or video |
| `media-src` | Audio and video sources | Playing hosted media |
The default policy trusts the Salesforce origin and nothing else, with a few Salesforce-managed exceptions. Your component can load anything served from the org itself, such as static resources, without extra setup. Anything on another origin needs an explicit allowance.
Allowing external origins with CSP Trusted Sites
To permit an external origin, an admin adds it in Setup under CSP Trusted Sites. Each entry has these parts:
- A URL or host pattern, such as
https://api.example.com. - A set of directives the origin is allowed for, such as
connect-srcorimg-src. - A context, which says where the entry applies (for example Lightning Experience, Experience Builder sites, or all contexts).
- An active flag.
Grant only the directives you need. An entry for connect-src lets your code send data to that host, which is a different risk from letting the page display an image from it.
Changes take effect for new page loads. After you add an entry, hard-refresh the page before testing again, or you may chase an error that is already fixed.
A browser call that needs a trusted site
The component below calls an external JSON API from the browser. It works under LWS only if https://api.example.com is a CSP Trusted Site with connect-src enabled.
import { LightningElement } from 'lwc';
export default class ExternalStatus extends LightningElement {
status = 'Not loaded';
errorMessage;
async handleLoad() {
this.errorMessage = undefined;
try {
const response = await fetch('https://api.example.com/v1/status');
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
this.status = data.state;
} catch (error) {
// A CSP block and a network failure both surface as a rejected fetch.
this.errorMessage = error.message;
console.error('Status request failed', error);
}
}
}The matching template:
<template>
<lightning-button label="Load status" onclick={handleLoad}></lightning-button>
<p>Status: {status}</p>
<template lwc:if={errorMessage}>
<p>Error: {errorMessage}</p>
</template>
</template>When CSP blocks the request, fetch rejects with a generic TypeError such as "Failed to fetch". The message does not name CSP. The browser console prints the real reason, which looks like this:
Refused to connect to 'https://api.example.com/v1/status' because it violates the following Content Security Policy directive: "connect-src 'self' ..."Always check the console. The error your JavaScript receives is intentionally vague, and it looks the same as a DNS failure or a missing CORS header.
CSP is not CORS
Adding a Trusted Site does not satisfy the server's cross-origin rules. These are separate checks.
- CSP is the page's policy about where it may connect. The browser applies it before the request is sent.
- CORS (Cross-Origin Resource Sharing) is the remote server's policy about which origins may read its responses. The browser applies it after the response arrives.
For a browser call to an external API, you need both: a Trusted Site in Salesforce, and the API returning an Access-Control-Allow-Origin header that includes your Salesforce origin. If CSP is fine but CORS fails, the console message mentions "CORS policy" rather than "Content Security Policy". The fix is on the remote server, or you can route the call through Apex and avoid the browser restrictions.
Scripts, styles, and inline code
LWS lets you run third-party libraries, but CSP still decides where those libraries may come from. The practical rules:
- Load scripts and stylesheets through
loadScriptandloadStylefromlightning/platformResourceLoader, using a static resource. The file is served from the org's origin, soscript-srcandstyle-srcare already satisfied. - Do not point
loadScriptat a CDN URL and expect it to work. External script hosts are blocked unless the context's CSP explicitly allows them, and the standard Lightning policy does not. Download the library and upload it as a static resource instead. - Inline
<script>elements and inline event handler attributes such asonclick="..."are not allowed in component templates. LWC templates useonclick={handler}, which binds a JavaScript function and is not an inline script. - Code that builds scripts from strings, such as
evalandnew Function, is a common failure point. Some libraries use these internally. If a library breaks only in Salesforce, search its source for them.
The static resource pattern from the third-party libraries chapter satisfies CSP by design. Here is a small variant that loads a script and a stylesheet together and reports which one failed:
import { LightningElement } from 'lwc';
import { loadScript, loadStyle } from 'lightning/platformResourceLoader';
import WIDGET_JS from '@salesforce/resourceUrl/widgetJs';
import WIDGET_CSS from '@salesforce/resourceUrl/widgetCss';
export default class WidgetHost extends LightningElement {
initialized = false;
async renderedCallback() {
if (this.initialized) {
return;
}
this.initialized = true;
const results = await Promise.allSettled([
loadScript(this, WIDGET_JS),
loadStyle(this, WIDGET_CSS)
]);
results.forEach((result, index) => {
if (result.status === 'rejected') {
const name = index === 0 ? 'script' : 'stylesheet';
console.error(`Widget ${name} failed to load`, result.reason);
}
});
}
}Promise.allSettled keeps one failure from hiding the other, so you see exactly which resource the platform rejected.
Images, fonts, and frames
Resources that your template references directly are checked against CSP too, with no JavaScript involved.
- An
<img>pointing at an external host needs that host trusted forimg-src. A static resource image needs nothing. - A web font referenced from a stylesheet needs
font-srcfor the font host andstyle-srcfor the stylesheet host. - An
<iframe>with an externalsrcneedsframe-src. Separately, the framed site must permit being embedded. Many sites sendX-Frame-Optionsor aframe-ancestorsrule that blocks embedding, and no Salesforce setting can override that.
These failures are silent in the UI: the image is missing or the frame is blank. Again, the console holds the violation message.
Experience Cloud sites and CSP levels
Experience Cloud sites let an admin choose how strict the site's CSP is. Stricter settings block inline scripts and access to untrusted hosts. Looser settings allow more, at the cost of a weaker defense against script injection. Under a strict setting, a Trusted Site entry for a script-src host may not behave as it does in the internal Lightning Experience.
Test in the same context your users will use. A component that works in the internal app can fail in a site because the site's CSP level or its Trusted Sites context differs. Check that the entry's context includes the site, and check the site's security settings before you debug your code.
A diagnostic routine
When something that "should work under LWS" does not, work through these steps in order.
- Open the browser developer console and reproduce the failure.
- Look for a line starting with
Refused to .... That is a CSP violation. Note the directive name in the message (connect-src,img-src, and so on) and the blocked URL. - If there is a CSP violation, add or correct a CSP Trusted Site for that host and directive, in the right context. Reload and retest.
- If the message mentions CORS, the fix belongs on the remote server, or move the call to Apex.
- If there is no violation message but you see a distortion error, an undefined property, or a library initialization failure, the cause is the LWS sandbox. That is a code or library problem, not a policy setting.
The directive name in the message tells you what to change. Do not widen the policy beyond it. If a connect-src violation appears, adding script-src access fixes nothing and grants more than you need.
Security guidance
- Trust the narrowest origin that works: a specific host, not a wildcard for a whole domain you do not control.
- Prefer static resources over trusted external script hosts. A static resource is a fixed file you reviewed, and a trusted host can change what it serves.
- Treat every Trusted Site as part of your app's attack surface. Review the list periodically and deactivate entries that are no longer used.
- Never rely on CSP alone for secrets. A trusted
connect-srchost can receive anything your component sends, so keep credentials on the server and use Named Credentials in Apex.
Exercise
A component calls fetch('https://api.partner.com/data') and the promise rejects with "Failed to fetch". The console shows: Refused to connect to 'https://api.partner.com/data' because it violates the following Content Security Policy directive: "connect-src 'self'". What should you change, and why would it be wrong to load the library from a different place or rewrite the code to avoid fetch?
Show answer
Add api.partner.com as a CSP Trusted Site with the connect-src directive enabled, in a context that covers where the component runs, then hard-refresh and retest. The message names connect-src, so the browser's CSP blocked the connection, not the LWS sandbox. Changing how the code calls the API (XMLHttpRequest, a library) would hit the same connect-src rule. If the partner server also lacks an Access-Control-Allow-Origin header for your org's origin, a CORS error will appear next, and that fix belongs on the partner server or in an Apex callout.
Exercise
A component uses loadScript with the URL https://cdn.example.com/lib.min.js and the library never loads. Name two ways the fix differs from the previous exercise, and say what you would do.
Show answer
Loading a script from an external host is blocked by script-src, and the standard Lightning policy does not let you simply trust a script CDN the way you trust a connect-src host. The preferred fix is to download the library, upload it as a static resource, and load it with loadScript using the @salesforce/resourceUrl import, which serves it from the org's own origin. If the library still fails after that, the console will show no CSP violation, and the cause is likely the LWS sandbox or a library that uses eval or new Function.