Sub topic 4
Lightning Locker compared with LWS
This chapter assumes you have read the earlier chapters on namespace isolation and on sandboxes and distortions. You should also be comfortable with basic LWC structure, async/await, and the idea that static resources are shipped in a package or org under a namespace. Here you will compare the two security architectures Salesforce has shipped for client-side component code, so you can decide what changes for you in practice.
Two answers to the same problem
Lightning Locker and Lightning Web Security (LWS) solve the same problem. Components from different namespaces run on the same page, in the same browser window, and they must not read each other's data or tamper with each other's DOM. Both architectures enforce this isolation by namespace, and both apply to your code without your calling any security API.
They differ in how they enforce it.
- Lightning Locker replaces the browser objects your code sees with wrapper objects. When your component asks for
window,document, or an element, it receives a "secure" stand-in such asSecureWindow,SecureDocument, orSecureElement. The wrapper forwards allowed operations to the real object and blocks or alters the rest. - Lightning Web Security runs each namespace's code in its own JavaScript sandbox. Inside the sandbox, your code uses mostly real browser objects. Where an API would break isolation, LWS applies a distortion, which is a replacement or restriction for that specific API. Only the dangerous parts are altered.
In short, Locker wraps the objects you touch, and LWS gives you a separate environment and patches the APIs that need patching.
What this means in practice
Object identity and type checks
Locker wrappers are different objects from the originals. Code that depends on identity can behave unexpectedly. Examples are comparing an element to a stored reference, checking instanceof against a built-in type, or passing a wrapped object to a library that inspects its internals.
Under LWS, most objects your code receives are the genuine ones, so these checks usually behave as they do in an ordinary page. This is the main reason many third-party libraries that failed under Locker work under LWS.
Library compatibility
Libraries often probe their environment. They look at window, document, prototypes, and global variables, and then pick a code path. Under Locker, the wrapped objects can send a library down the wrong path or break assumptions about property enumeration. Under LWS, the library sees an environment much closer to a normal browser, so fewer libraries need patching.
LWS is not a guarantee, though. A library that writes to a global and expects another namespace to read it will still fail, because isolation is the point of the sandbox. A later chapter covers loading libraries from static resources in detail.
Performance
Wrapping every object adds work on each property access and method call. LWS avoids most of that cost, because only distorted APIs are intercepted. Salesforce positions this as one of the benefits of LWS, and the effect is most visible in components that touch the DOM or call web APIs heavily. Measure your own pages before and after a switch rather than assuming a number.
Standard API access
LWS supports more standard web APIs than Locker did, and it exposes them in a form closer to the standard. Some APIs are still distorted or blocked, and the next chapters cover them. Treat the Salesforce documentation for the supported API list as the reference, and check it against your release.
Side-by-side summary
| Aspect | Lightning Locker | Lightning Web Security |
|---|---|---|
| Isolation unit | Namespace | Namespace |
| Mechanism | Secure wrapper objects around browser objects | JavaScript sandbox per namespace with API distortions |
| What your code sees | Wrappers such as `SecureWindow` | Mostly real objects inside the sandbox |
| Third-party library compatibility | Often needs workarounds | Generally better |
| Overhead | Cost on wrapped object access | Cost mainly on distorted APIs |
| Applies to | LWC and Aura components | LWC and Aura components |
| Cross-namespace sharing | Public API and events | Public API and events |
What does not change
It is easy to over-read the differences, so note the rules that stay the same.
Query your own template
Under both architectures, a component reaches its own rendered elements through this.template. The code below works the same under either.
import { LightningElement } from 'lwc';
export default class FocusInput extends LightningElement {
handleClick() {
// Query only inside this component's own template.
const input = this.template.querySelector('lightning-input');
if (input) {
input.focus();
}
}
}Reaching out with document.querySelector to grab an element rendered by another component is not a supported pattern under either. It may return nothing, or it may break after a release.
Communicate with public APIs and events
Components in different namespaces cannot reach into each other's internals under Locker or LWS. They communicate through @api properties and custom events.
// child component (any namespace)
import { LightningElement, api } from 'lwc';
export default class ItemPicker extends LightningElement {
@api label;
handleSelect() {
this.dispatchEvent(
new CustomEvent('select', { detail: { id: '001' } })
);
}
}Keep detail to plain data such as strings, numbers, and simple objects. Passing live DOM nodes or objects owned by a library across a namespace boundary is a common source of errors in both models.
Treat globals as private to your namespace
Under both models, one namespace cannot rely on another namespace's window properties. A script that sets window.myLib for a component in a different namespace to pick up will not work.
A defensive pattern for loading code
Libraries are where you are most likely to see a difference between the two architectures. Wrap initialization in try/catch and log the error message, so a failure shows up in the console instead of leaving a blank component.
import { LightningElement } from 'lwc';
import { loadScript } from 'lightning/platformResourceLoader';
import CHART_JS from '@salesforce/resourceUrl/chartjs';
export default class ChartHost extends LightningElement {
libraryLoaded = false;
async renderedCallback() {
if (this.libraryLoaded) {
return;
}
this.libraryLoaded = true;
try {
await loadScript(this, CHART_JS);
const canvas = this.template.querySelector('canvas');
this.chart = new window.Chart(canvas, {
type: 'bar',
data: { labels: ['A'], datasets: [{ data: [1] }] }
});
} catch (error) {
// Surface sandbox or load failures instead of failing silently.
console.error('Chart library failed to load or initialize', error);
}
}
}The libraryLoaded flag matters because renderedCallback runs after every render. Without it, the component would try to load and initialize the library repeatedly.
Note that loadScript loads the library into the sandbox of the namespace that owns the component. Another namespace's components do not see window.Chart from your load, and the reverse also holds.
The architectures are chosen per org or site
Locker and LWS are not options you pick per component. Salesforce enables the choice for the org, and for Experience Cloud sites it can be set on the site. That has two consequences.
- Your components run under whichever architecture the target org uses. A managed package you ship can land in an org with Locker or an org with LWS.
- A component that works under one should be tested under the other, if you distribute it or if you plan a migration.
Enabling LWS is covered in the next chapter, and migration is covered later in the tutorial.
Behavior differences to expect
When you move a component from Locker to LWS, these are the practical changes to watch for.
- Fewer workarounds. Code written specifically to get around a wrapper quirk may become unnecessary. Some of it may even misbehave, so retest it.
- Different error text. Locker errors often mention secure wrappers or "access denied" on a wrapped object. LWS errors are phrased in terms of the sandbox or a distorted API.
- Different stack traces. With Locker, frames from the wrapper layer appear in traces. With LWS they largely do not.
- Same isolation guarantees. Cross-namespace DOM and global access stays blocked. If a component was reading another namespace's DOM and that was blocked before, it will not start working now.
Common mistakes in the comparison
- Assuming LWS removes isolation. It does not. It enforces the same namespace boundary with a different mechanism.
- Assuming "real objects" means "all APIs". Distortions still exist, and some APIs remain restricted.
- Testing in one org only. Behavior is governed by the org or site setting, so a package should be checked under both settings.
- Keeping Locker-era workarounds without retesting. A shim that mutated or unwrapped objects may now touch a real object and have side effects.
- Mixing it up with CSP. Content Security Policy controls which sources of script and resources the browser permits. It is a separate layer, covered in its own chapter.
Exercises
Exercise
In one or two sentences, describe the main mechanical difference between how Lightning Locker and Lightning Web Security enforce namespace isolation.
Show answer
Locker gives component code secure wrapper objects (such as SecureWindow and SecureElement) in place of the real browser objects. LWS runs each namespace's code in its own JavaScript sandbox, where it uses mostly real objects and only specific APIs are distorted.
Exercise
A teammate's component sets window.sharedConfig = {...} in a package from namespace acme, and a component from namespace beta reads window.sharedConfig. This worked in neither Locker nor LWS. Why, and what should they use instead?
Show answer
Each namespace has its own sandbox global under LWS (and its own SecureWindow under Locker), so a property set in one namespace is not visible in another. They should pass the data through a public @api property or a custom event, or use a Lightning Message Service channel.
Exercise
A charting library fails under Locker because it inspects wrapped objects, but initializes correctly after the org switches to LWS. Name one reason that could explain the change, and one thing that would still fail under LWS.
Show answer
Under LWS the library sees mostly real browser objects, so its environment checks and type checks succeed. A library that depends on reading a global written by a script in another namespace would still fail, because LWS keeps namespaces isolated.