Sub topic 10
Content Security Policy and LWS
This chapter assumes you know basic LWC structure, async/await, and what an HTTP request to a third-party host looks like. It also assumes you have read the earlier chapters on sandboxes, DOM access, and static resource libraries.
Two layers, two jobs
Lightning Web Security (LWS) and Content Security Policy (CSP) are separate controls. They run at different points and stop different problems.
- LWS runs inside the page. It sandboxes JavaScript per namespace and distorts APIs so one namespace cannot read another's data.
- CSP is a browser feature that Salesforce turns on with HTTP response headers. The browser enforces it. It limits which origins the page may load scripts, images, fonts, frames, and network connections from.
Turning on LWS does not loosen CSP. Code that LWS permits can still be blocked by CSP, and the reverse is also true.
What CSP restricts in Lightning
Salesforce sends a CSP header on Lightning pages. Its effects on components are:
- Inline scripts and
eval-style code execution are blocked. Strings passed toeval,new Function, orsetTimeoutas code will fail. - Scripts load only from the page's own origin. For third-party code, put the library in a static resource and load it with
loadScript, as shown in the previous chapter. - Network connections (
fetch,XMLHttpRequest, WebSocket) are limited to your Salesforce origin and to hosts you list as trusted. - Images, fonts, frames, media, and styles from other hosts each need a matching trusted entry.
Allowing an external host
You allow an external host in Setup under Trusted URLs (older orgs may show "CSP Trusted Sites"). Each entry has a URL and a set of directives:
| Directive | Controls |
|---|---|
| `connect-src` | `fetch`, XHR, WebSocket |
| `img-src` | Images |
| `font-src` | Web fonts |
| `frame-src` | Iframes |
| `media-src` | Audio and video |
| `style-src` | External stylesheets |
Enable only the directives you need, and list the narrowest URL that works. A broad entry such as a whole domain widens what every component on the page can reach.
A client call that needs a trusted URL
This component calls a public API from the browser. It works only after https://api.example.com is added as a Trusted URL with connect-src enabled.
import { LightningElement } from 'lwc';
export default class StatusFetcher extends LightningElement {
status = '';
errorMessage = '';
async handleLoad() {
try {
const response = await fetch('https://api.example.com/status');
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
this.status = data.state;
} catch (error) {
// A CSP block surfaces as a generic network error (TypeError).
this.errorMessage = error.message;
console.error('Status request failed', error);
}
}
}When CSP blocks the call, fetch rejects with a generic TypeError such as "Failed to fetch". The useful detail is in the browser console, which logs a message beginning "Refused to connect to ... because it violates the following Content Security Policy directive". Read that line first. It names the directive and the blocked origin.
Telling LWS errors from CSP errors
The two failures look different, and the difference decides where you fix the problem.
| Symptom | Likely cause | Fix |
|---|---|---|
| Console says "Refused to ... violates the following Content Security Policy directive" | CSP | Add or correct a Trusted URL with the right directive |
| Generic `TypeError: Failed to fetch` and a CSP line in the console | CSP, `connect-src` | Add the host with `connect-src` |
| JavaScript error thrown from a library, such as an undefined global or a blocked property | LWS sandbox or distortion | Change your code, or choose a different library version |
| Library script fails to load from an external URL | CSP script restrictions | Upload it as a static resource and use `loadScript` |
Exercise
A component calls fetch('https://maps.example.org/geocode'). The call fails with "Failed to fetch", and the console shows a CSP violation for connect-src. Which fix applies, and why would changing the component's JavaScript not help?
Show answer
Add https://maps.example.org as a Trusted URL with the connect-src directive enabled. The browser enforces CSP at the network layer, and LWS is not the cause. The request is valid JavaScript that LWS allows, so editing the component cannot change the browser's decision.