Sub topic 13
Lightning Web Security and component isolation
This chapter assumes you can build a basic Lightning web component, read JavaScript classes and modules, and know the difference between Aura and LWR sites from earlier chapters. You will learn what Lightning Web Security (LWS) does in a site, which code patterns it breaks, and how to write components that work under it.
What Lightning Web Security does
Lightning Web Security is the browser-side security architecture for Lightning web components. A site page can hold components from several sources: your own, those from managed packages, and those from Salesforce. Without isolation, any of them could read another's data from the DOM or from global objects.
LWS prevents this with JavaScript sandboxes. A sandbox is a separate copy of the global JavaScript environment (window, document, and built-in objects). Salesforce creates one sandbox for each namespace. Components in the same namespace share a sandbox. Components from different namespaces cannot reach each other's objects or DOM.
Inside each sandbox, LWS applies distortions. A distortion is a replacement for a standard browser API that adds a safety check or removes unsafe behavior. For example, document in your component is a version that does not let you walk into another namespace's elements.
LWS and Lightning Locker
Lightning Locker is the older isolation model. It wraps objects in secure wrapper classes, such as a secure element, and these wrappers can behave differently from the real objects. LWS instead uses the standard APIs inside a sandbox and distorts only the parts that need it. As a result, more third-party libraries work unchanged.
| Aspect | Lightning Locker | Lightning Web Security |
|---|---|---|
| Isolation method | Secure wrapper objects | Per-namespace JavaScript sandbox with distortions |
| Third-party library compatibility | Often needs workarounds | Generally better, since standard APIs are used |
| Aura sites | Available | Available, turned on in Session Settings |
| LWR sites | Not available | Always used |
The runtime from the earlier chapter decides your options. An LWR site always runs under LWS. For an Aura site, an admin turns LWS on in Setup under Session Settings, with the option to use Lightning Web Security for Lightning web components and Aura components. The setting applies to the whole org, so test other apps in the org before you switch it.
What LWS does not protect
LWS runs in the visitor's browser. A visitor controls their browser and can alter any JavaScript on the page. LWS therefore protects components from each other. It does not protect your data from a visitor.
Data protection happens on the server. Use the sharing rules, object and field permissions, guest user settings, and WITH USER_MODE queries from the earlier chapters on Apex and guest security. Never hide data from a guest by only not rendering it in a template.
Writing code that works under LWS
Most components run unchanged. Problems come from code that reaches outside the component's own template or assumes access to every global.
Query only your own template
Use this.template.querySelector to find elements that your component renders. Calling document.querySelector searches the document, and LWS limits what that can return.
import { LightningElement } from 'lwc';
export default class StatusBanner extends LightningElement {
renderedCallback() {
// Works: searches only this component's rendered template.
const banner = this.template.querySelector('.banner');
if (banner) {
banner.classList.add('is-visible');
}
// Avoid: searches the whole document and may return
// nothing or fail, because other namespaces are off limits.
// const other = document.querySelector('.banner');
}
}Insert manual DOM only inside a manual container
Lightning web components control their own DOM. If you need to add elements with appendChild or innerHTML, mark a container with lwc:dom="manual" and write only inside it.
<template>
<div class="host" lwc:dom="manual"></div>
</template>import { LightningElement } from 'lwc';
export default class ManualNote extends LightningElement {
rendered = false;
renderedCallback() {
if (this.rendered) {
return;
}
this.rendered = true;
const host = this.template.querySelector('.host');
const note = document.createElement('p');
note.textContent = 'Added after render.';
host.appendChild(note);
}
}The rendered flag stops the note from being added again each time the component re-renders. Use textContent for text from users or from records. Assigning that text to innerHTML opens the page to script injection.
Load third-party libraries from static resources
Upload the library as a static resource and load it with loadScript from lightning/platformResourceLoader. The library's globals live in your namespace's sandbox, so your own components can use them, and components from other namespaces cannot.
import { LightningElement } from 'lwc';
import { loadScript } from 'lightning/platformResourceLoader';
import SOME_LIB from '@salesforce/resourceUrl/someLib';
export default class LibUser extends LightningElement {
error;
ready = false;
async connectedCallback() {
try {
await loadScript(this, SOME_LIB);
this.ready = true;
} catch (e) {
this.error = e;
}
}
}Here someLib stands for a static resource you created. Always handle the rejected promise. A script can fail to load because of a missing resource, a network error, or a Content Security Policy block, and the component should show a message instead of staying blank.
Content Security Policy
LWS controls which objects your code can touch. Content Security Policy (CSP) is a separate browser rule that controls which locations a page may load scripts, styles, images, and data from. Both apply to a site.
- Scripts from your own static resources are allowed.
- Scripts or API calls to an outside host fail unless an admin adds that host as a CSP Trusted Site in Setup.
- Inline scripts and
eval-style code are blocked in most cases.
Adding a Trusted Site for a host lets every component on the site contact it. Add only hosts you control or trust fully.
Cross-namespace boundaries
Because sandboxes are per namespace, a few things behave differently from plain JavaScript.
- A global variable set by one namespace is not visible to another. Do not use
windowas a message bus between a custom component and a packaged one. - Components talk through the supported channels. These are public
@apiproperties and methods, custom events, and Lightning Message Service where the runtime supports it. - Objects that cross a namespace boundary can be wrapped or restricted. If a value from a packaged component looks different or fails an identity check, copy the data you need into a plain object.
Debugging isolation errors
When LWS blocks an operation, the browser console usually shows an error or a null result at the point of access. A repeatable method helps.
- Open the browser developer tools on the published site or a preview, and read the first console error. Later errors are often caused by it.
- Find the line that touches
document,window, or a global library, and check whether it reaches outside your template. - Replace it with
this.template.querySelector, a public property, or an event. - If a library fails, check whether it expects a global it cannot see. Test it in a small component to confirm.
- Confirm which runtime the site uses. A component that works in an Aura site with Locker off may fail in an LWR site.
Summary of rules
- Use
this.template.querySelector, notdocument.querySelector, for your own elements. - Add manual DOM only inside a
lwc:dom="manual"container, and write user text withtextContent. - Load libraries from static resources with
loadScriptand handle failure. - Do not share state through
window. Use@api, events, or Lightning Message Service. - Keep server-side access control in Apex and platform settings.
Exercise
A component calls document.querySelector('.price') and works in a sandbox org with Locker on but returns null on an LWR site. What is the likely cause, and what is the fix?
Show answer
LWR sites always use Lightning Web Security, which limits what document can reach across the page. The component should search only its own template, using this.template.querySelector('.price'), after the element has rendered (for example in renderedCallback).
Exercise
A teammate hides a "Delete case" button from guest users with a template condition that checks isGuest, and says LWS keeps guests from deleting cases. Is that correct?
Show answer
No. LWS isolates components from each other in the browser. It does not enforce data access, and a visitor can change client-side code. The delete must be controlled on the server through guest user and profile permissions, sharing, and Apex that uses with sharing and WITH USER_MODE or equivalent checks.
Exercise
Your component needs to call a third-party API at an outside host from the browser, and the call fails on the published site with no error from your code. Which setting should you check first?
Show answer
Check whether the host is listed as a CSP Trusted Site in Setup. Content Security Policy blocks connections to hosts that are not trusted, and this is separate from LWS.