Sub topic 3
Sandboxes and Distortions: How LWS Changes What Code Can Do
This chapter assumes you can build a basic Lightning web component (HTML template, JavaScript class, metadata file) and that you know modern JavaScript, including modules, classes, and async/await. It also assumes you know what the same-origin policy is and what a Salesforce namespace is. The previous chapter covered how LWS separates code by namespace. This chapter covers the mechanism that does the separating: sandboxes and distortions.
The Core Idea
Lightning Web Security (LWS) does not run your component in a separate iframe or a separate browser process. Your component runs in the same page as every other component. LWS changes what your code sees when it touches the browser's built-in objects.
It does this with two pieces:
- A sandbox is a separate JavaScript environment, created for one namespace. Code in that sandbox gets its own copy of the global objects, such as
window,document, andArray. - A distortion is a replacement for a standard browser API. When your code calls the API, it gets the replacement. The replacement checks whether the call is safe and either runs it, changes it, or blocks it.
The sandbox keeps namespaces apart. Distortions keep code inside a sandbox from reaching things it should not.
What a Sandbox Gives You
Each namespace gets its own sandbox. All components in the same namespace share that sandbox. Components in a different namespace use a different one.
Inside a sandbox, the global objects are separate copies. Two practical results follow.
- A global variable you set in one namespace is not visible to code in another namespace.
- If a library changes a built-in, for example by adding a method to
Array.prototype, the change stays in that namespace's sandbox. It cannot break code in another namespace.
Components in the same namespace do share a sandbox. They can see each other's globals. Do not use that as a communication channel. Chapter later in this tutorial on cross-namespace sharing covers the supported approach, and it works for same-namespace components too.
Here is a small example. Suppose a component in your c namespace runs this.
import { LightningElement } from 'lwc';
export default class GlobalWriter extends LightningElement {
connectedCallback() {
window.myAppSetting = 'enabled';
console.log(window.myAppSetting); // 'enabled'
}
}The log prints enabled because the read happens in the same sandbox as the write. A component from another namespace that reads window.myAppSetting gets undefined. Code outside any sandbox, such as the browser's developer console, does not see the value on the real window either.
What a Distortion Does
A distortion sits between your code and a browser API. Think of it as a wrapper with rules. The page's real API still exists, but your code gets the wrapper.
A distortion can do one of three things.
| Action | What happens | Example effect |
|---|---|---|
| Allow | The call passes through unchanged. | Most pure JavaScript, such as `Math.max`, is not changed. |
| Modify | The call runs, but arguments or results are altered or restricted. | A DOM query returns only elements your namespace is allowed to see. |
| Block | The call fails with an error or does nothing. | An API that could read another namespace's data is not permitted. |
Distortions apply to many areas, including DOM access, network and storage APIs, and some global properties. You do not configure them. Salesforce defines them, and they apply to every component in the org once LWS is on.
Why Distortions Exist
A sandbox on its own is not enough. Some browser APIs reach outside the sandbox. For example, document represents the whole page. Without a distortion, document.querySelector('div') could return an element that belongs to another namespace's component. A distortion makes that call return only what your namespace is allowed to see.
The browser's own security model does not solve this problem. The same-origin policy separates pages from different origins. All Lightning components on a page share one origin, so the browser treats them as equally trusted. LWS adds the missing separation inside the page.
Seeing Distortions in Practice
A distortion is easiest to notice through its effects. Consider DOM access.
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();
}
}
}this.template.querySelector searches the component's own template. That is the supported pattern, and it works the same under LWS. A global query such as document.querySelector('lightning-input') is different. Under LWS the result can be restricted, so you should not rely on it to find elements in your own or other components. The next chapters on DOM access cover the exact rules.
A second effect is on error behavior. Blocked operations can raise errors that you would not see in a plain browser page. When code works in a local test page but fails in Salesforce, a distortion is one possible cause.
Sandbox Boundaries and Shared Objects
Objects can cross a sandbox boundary. When they do, LWS has to decide how the other side sees them. The usual model is that the receiving code gets a safe view of the object, not the raw original.
Two consequences matter in daily work.
- Identity checks can differ. A comparison such as
a === bcan returnfalsefor two references that point to the same underlying object if one passed through a boundary and the other did not. Compare by a stable key such as an Id instead. - Prototype checks can differ.
instanceofmay fail when an object was created in a different sandbox. For example,value instanceof Arraycan befalsefor an array that came from another namespace. UseArray.isArray(value)instead, because it does not depend on which sandbox created the array.
The following example shows the safer pattern.
export function toList(value) {
// Array.isArray works for arrays created in any sandbox.
if (Array.isArray(value)) {
return value;
}
return value == null ? [] : [value];
}This function treats arrays from any source the same way. It also gives a predictable result for null and undefined.
Where Libraries Fit
Third-party libraries from static resources load with loadScript. They run in the sandbox of the namespace that loads them. The library sees the same distorted APIs as your component. This is why a library that assumes it can read the whole page, or change global objects widely, may fail under LWS.
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);
}
}
}Note two points. The library attaches Chart to window, and your component reads it from window. That works because both run in the same namespace sandbox. The try/catch makes sandbox-related failures visible. A later chapter covers libraries in detail.
Same-Namespace Sharing and Cross-Namespace Boundaries
Because sandboxes are per namespace, the boundary that matters for communication is the namespace boundary. Components across it should use public properties and events. A child exposes data with @api and notifies its parent with a CustomEvent.
// 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' } })
);
}
}This works under a sandbox because the data crosses through the component's public interface. It does not reach into the other component's DOM or globals. Keep detail values to plain data, such as strings, numbers, and simple objects. Plain data survives a boundary crossing most reliably.
A Debugging Checklist
When code behaves differently in Salesforce than in a plain browser page, work through these steps.
- Check whether the code reads or writes a global, such as
window.something, that another namespace might also use. - Check whether it queries
documentand expects to find elements outside your own template. - Replace
instanceofchecks on values from outside your namespace withArray.isArrayor checks on properties. - Replace
===on objects that may have crossed a boundary with a comparison on an Id or another stable key. - Look at the browser console for an error message that names the blocked operation.
- If a library is involved, test it in a minimal component with
try/catcharoundloadScriptand initialization.
Common Mistakes
- Assuming a global is shared. A value set on
windowin namespaceacmeis not visible inc. Use public properties and events. - Treating the sandbox as a security guarantee for your own data. Components in the same namespace share one sandbox. Do not store secrets on
windowand assume other same-namespace code cannot read them. - Querying
documentfrom a component. Usethis.template.querySelectorfor elements in your own template. - Blaming LWS for every failure. A failing call might be an ordinary bug. Confirm by reading the error and isolating the call.
Summary of the Model
- A sandbox is a per-namespace JavaScript environment with its own global objects.
- A distortion replaces a browser API with a version that allows, modifies, or blocks the call.
- Together they create separation inside a single page, where the browser's same-origin policy does not.
- Components share data across namespaces through
@apiproperties and custom events. - Cross-boundary objects can fail
===andinstanceofchecks, so preferArray.isArrayand stable keys.
Exercise
A component in namespace acme runs window.theme = 'dark'. A component in namespace c then reads window.theme. What does the second component get, and what is the supported way to pass the theme value to it?
Show answer
The c component gets undefined, because each namespace has its own sandbox with its own window globals. The supported way is to pass the value through a public @api property on the receiving component, or to send it with a CustomEvent whose detail holds the value.
Exercise
A helper checks if (records instanceof Array) and fails for a list passed in from a component in another namespace. Why can this happen, and what should replace the check?
Show answer
The array was created in a different sandbox, which has its own Array constructor, so instanceof Array in the receiving sandbox can return false. Replace the check with Array.isArray(records), which does not depend on which sandbox created the array.