Sub topic 2
How LWS Isolates Code by Namespace
Lightning Web Security (LWS) decides which components may touch each other's data by grouping them by namespace. This chapter explains that grouping and what it means for the code you write.
This chapter assumes you can read a Lightning web component (HTML template, JavaScript class, metadata file) and use modern JavaScript (modules, classes, async/await). It also assumes you know what the same-origin policy is and what a Salesforce namespace is. The chapter on why component code needs isolation covers the threat model, so this one goes straight to the mechanism.
The Unit of Isolation Is the Namespace
All Lightning components on a page run in the same browser tab, on the same origin, in the same JavaScript engine. The browser alone would let any of them read window, patch built-in prototypes, or walk the DOM of another component. LWS prevents this by giving each namespace its own JavaScript sandbox.
A namespace is the prefix in a component's name. In c-item-picker, the namespace is c. In acme-gauge, it is acme. Components from different sources land in different namespaces:
- Components you create in your own org, with no namespace of your own, use the default
cnamespace. - A managed package installed in your org brings its own namespace, such as
acme. - Salesforce's base components use the
lightningnamespace, and other Salesforce-provided code has its own namespaces.
LWS creates one sandbox for each namespace it needs on the page. Every component in that namespace runs inside the same sandbox, and components in other namespaces run inside their own.
What a Sandbox Contains
A sandbox is a separate JavaScript environment inside the page. It has its own global object, which components see as window. It also has its own copies of the built-in objects, such as Object, Array, Promise, and Function. This matters for two reasons.
- A property you attach to
windowlands on your namespace's global, not the real browser global. Another namespace never sees it. - If code in another namespace patches
Array.prototypeorObject.prototype, your sandbox's copies are unaffected.
LWS also changes how some browser APIs behave. It does this with distortions: small replacements that wrap or restrict a specific API inside the sandbox. A distortion might block an unsafe API, or it might scope one to the calling namespace. The next chapter covers distortions in detail. For now, remember that the sandbox gives each namespace a separate environment, and distortions adjust the APIs inside it.
Under the hood, LWS uses a membrane. A membrane is a layer that sits between two JavaScript environments and wraps every object that passes between them. Salesforce built this on its open-source near-membrane library. Components never hold a raw reference to an object from another sandbox. They hold a wrapper (a proxy) that forwards operations and applies the rules.
Who Shares a Sandbox
The table below summarizes how sandboxes line up with code on a page.
| Code | Namespace | Sandbox | Can read your `window` globals? |
|---|---|---|---|
| Your component `c-order-form` | `c` | The `c` sandbox | Yes, if it is also in `c` |
| Your component `c-item-picker` | `c` | The `c` sandbox | Yes, if it is also in `c` |
| Managed package component `acme-gauge` | `acme` | The `acme` sandbox | No |
| Base component `lightning-input` | `lightning` | The `lightning` sandbox | No |
Two components in c can therefore share state through a global, a module-level variable in a shared module, or a property on window. This is allowed, because they are in the same trust boundary. It is rarely a good design, since it hides dependencies. The rest of this chapter focuses on what the boundary blocks.
Walkthrough: A Global That Does Not Cross
Suppose a component in your org sets a flag on window:
import { LightningElement } from 'lwc';
export default class FlagSetter extends LightningElement {
connectedCallback() {
// Sets the property on the c namespace's global object.
window.orderFlowStarted = true;
}
}A second component in the same c namespace can read that flag:
import { LightningElement } from 'lwc';
export default class FlagReader extends LightningElement {
connectedCallback() {
// Same namespace, same sandbox, same global object.
console.log('c sees:', window.orderFlowStarted); // true
}
}A component from the acme package that runs the same console.log('acme sees:', window.orderFlowStarted) line prints undefined. The property exists only on the c sandbox's global. The acme sandbox has its own window, and nothing set it there.
This is the behavior LWS is designed to produce. A package author cannot read your globals, and you cannot read theirs.
Crossing the Boundary
Isolation would be useless if components could not talk to each other. LWS keeps the supported paths from LWC, which are public properties and events. The membrane makes both work across sandboxes.
A public property is a field or accessor decorated with @api. A parent sets it, and the child reads it. An event is a CustomEvent that a child dispatches and a parent listens for. Here is a child that is safe to use from any namespace:
// 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' } })
);
}
}When a parent in another namespace passes a value into label, or receives event.detail, the value passes through the membrane. Primitives such as strings, numbers, and booleans arrive as they are. Objects and functions arrive wrapped. The wrapper behaves like the original for normal reads, writes, and calls, so most code works without changes.
Gotchas at the Boundary
- Identity. A wrapped object is a proxy, not the original. Comparing a wrapper against an object you hold from your own sandbox with
===can be false. Compare ids or other primitive fields instead. - Prototypes. An array that arrives from another sandbox was built with that sandbox's
Array. PreferArray.isArray(value)tovalue instanceof Array, which can fail across realms in plain JavaScript. LWS wrappers soften this, butArray.isArrayis the safe habit. - Cost. Every operation on a wrapped object goes through a proxy. Passing a very large object and iterating it in a hot loop is slower than copying the fields you need once.
- Mutation. Objects that LWC passes into
@apiproperties are read-only inside the child, whatever the namespace. Copy the data before you change it.
Trade-offs and Failure Modes
Per-namespace sandboxes are a deliberate trade, and they fail in predictable ways.
What you gain. Third-party code cannot reach your data, and an unrelated namespace cannot break your page by patching a built-in. Compared with Lightning Locker, LWS lets components use more of the standard web platform, because isolation is enforced by separate environments instead of by hiding APIs behind wrappers. The Locker comparison appears later in this tutorial.
What you pay.
- Shared-global patterns stop working across namespaces. Code that sets a variable on
windowin a package and expects to read it from your component will seeundefined. - Libraries load into one sandbox. A script loaded with
loadScriptruns in the namespace of the component that loaded it. Another namespace on the page does not see that library. If two namespaces both need it, each must load it. - Proxies add overhead and edge cases. Large payloads, identity checks, and unusual object types can behave differently when they cross.
- Same-namespace code is not isolated from itself. Two components in
ccan still interfere with each other. A bug in one can corrupt a shared global the other relies on.
Common Errors
- Using
windowas a message bus across namespaces. Symptom: a value set in one component isundefinedin another. Cause: the components are in different namespaces and have different global objects. Fix: pass the value through an@apiproperty or an event. - Assuming a library loaded by a managed package is available to your code. Symptom:
window.SomeLib is undefinedin your component even though the page clearly loaded it. Fix: load it yourself withloadScriptfrom your own component, so it lands in your sandbox. - Comparing objects from different namespaces with
===. Symptom: an equality check that you expect to be true returns false. Fix: compare stable ids. - Testing only in the
cnamespace. Symptom: a component works in your org and fails after it is packaged under a new namespace. Cause: you had accidentally relied on a sharedcglobal. Fix: test the packaged component, and pass data explicitly.
Checking Which Sandbox You Are In
A quick way to confirm isolation in your own org is to compare a marker on window from two namespaces. Set a unique property in a component, read it from a second component in another namespace, and log both results. If the second reads undefined, the two components are in separate sandboxes. Remove the marker afterward, since it was only a diagnostic.
Exercise
A component in your org (c-report) sets window.currentFilter = 'open'. A component from the managed package acme (acme-chart) logs window.currentFilter and prints undefined. Explain why, and describe a supported way to give acme-chart the filter value.
Show answer
Under LWS, c-report and acme-chart run in different sandboxes because they have different namespaces (c and acme). Each sandbox has its own global object, so the property set on the c sandbox's window does not exist on the acme sandbox's window. To share the value, expose a public property on acme-chart with @api (for example @api filter), and have c-report pass 'open' to it in its template. If acme-chart needs to send data back, it should dispatch a CustomEvent that c-report handles.
Exercise
Two components, c-header and c-footer, are both in the c namespace. Can c-footer read a property that c-header set on window? Name one reason you might still avoid doing this.
Show answer
Yes. Both components are in the c namespace, so they run in the same sandbox and share one global object. You might still avoid it because the dependency is hidden. If either component is later moved into a package with its own namespace, the shared global stops working without any error beyond an undefined value. Public properties and events make the dependency explicit and keep working across namespaces.