How do Content Security Policy (CSP) Trusted Sites protect Lightning Web Components during external API communications?
Answer
Basics: Salesforce sends a Content-Security-Policy header with Lightning Experience and Experience Cloud pages. A browser enforcing it refuses to make requests to, or load content from, hosts not listed. If your LWC calls fetch('https://api.partner.com') from the browser, or displays an image or iframe from another domain, you must add that host or the browser console shows a CSP violation.
How it works:
- Setup, Security, CSP Trusted Sites (or Trusted URLs), New.
- Enter name, URL (HTTPS recommended), and tick the directives it should apply to: connect-src (fetch/XHR/WebSocket), img-src, font-src, style-src, frame-src, media-src.
- Set context (Lightning/Aura, Experience Builder sites, or all) and Save.
- Salesforce adds the host to the matching directives in the response header; users get it on the next page load.
Advanced / deep dive: CSP is a browser-side control and is different from Remote Site Settings or Named Credentials, which authorize server-side Apex callouts. A common mistake is adding a trusted site when the real need is server-side. For secrets or CORS-less APIs, call through Apex with a Named Credential instead of the browser: credentials stay on the server and CSP is not involved. For scripts, Lightning does not let you load arbitrary third-party JavaScript from a CDN; ship libraries as static resources and use loadScript. Lightning Web Security (the successor to Lightning Locker) provides separate JavaScript sandboxing. External hosts must also send CORS headers allowing the Salesforce origin for browser fetches. In Experience Cloud, the site's Security settings let you pick a CSP level and manage trusted sites too.
Code / config example:
Name: Partner_API
URL: https://api.partner.com
Directives: connect-src (scripts) = checked, img-src = checked
Context: All