Sub topic 1
Why Component Code Needs Isolation
Lightning Web Security (LWS) exists because many parties' JavaScript runs together in one browser page. This chapter explains that problem. It covers what the browser does and doesn't protect, what could go wrong without extra isolation, and what a solution has to provide. Later chapters cover how LWS does it.
Prerequisites
This chapter assumes you already have the following:
- Basic Lightning web component (LWC) structure: an HTML template, a JavaScript class, and a metadata file.
- Modern JavaScript: modules, classes, and
async/await. - A working idea of the same-origin policy, which the next section reviews.
- Awareness that Salesforce code can live in a namespace, and that static resources hold files such as JavaScript libraries.
You don't need any LWS knowledge. You also don't need to have used Lightning Locker.
The problem: one page, many authors
Open a record page in Lightning Experience and you see one browser tab with one document. That document is assembled from code written by different parties:
- Salesforce's own base components and framework code.
- Components your team wrote, usually in your org's namespace or no namespace.
- Components from managed packages you installed from AppExchange, each with its own namespace.
- Third-party JavaScript libraries that any of the above loaded from static resources.
All of this code runs in the same page, on the same origin, in the same JavaScript environment. If nothing separated these parties, any one of them could read what the others display, call the APIs they call, and change the objects they rely on.
The scenario is realistic. A package vendor may have good intentions and still ship a bug. A vendor may also be compromised, or a library may be tampered with upstream. Your org's administrators install the package, but the end user's session is what the code runs inside.
What the browser gives you, and what it doesn't
Browsers have a solid security model for separating websites from one another. Its core is the same-origin policy. An origin is the combination of scheme, host, and port. Code from https://a.example.com can't freely read the DOM or responses of https://b.example.com.
That policy answers the question "may this site read that site's data?" It does not answer "which script inside this page may read this page's data?" Every script that a page loads gets the same privileges as the page itself. In a normal web app that's acceptable, because one team controls all the scripts.
Lightning Experience is different. Salesforce serves components from your org's domain, so their JavaScript shares one origin and one window. The browser sees a single trusted page. It has no concept of "the package vendor's part of the page."
| Question | Who answers it |
|---|---|
| May a script on another site read this page? | The browser's same-origin policy |
| May a script in this page read this page's DOM? | Nobody by default. Yes, always. |
| May one component's code read another component's data? | Only a platform-level isolation layer |
The last row is the gap that Salesforce fills with its own isolation layer.
Shadow DOM is not a security boundary
LWC components use shadow DOM, or a polyfill called synthetic shadow, to encapsulate their markup. Encapsulation keeps styles from leaking and keeps document.querySelector from accidentally matching elements inside a component. It exists to help developers avoid accidental coupling. It isn't designed to stop code that is trying to get through. Treat it as good manners between cooperating developers, not as a wall against hostile code.
What could go wrong without isolation
Consider the kinds of damage that unisolated code in a shared page could do. These examples are illustrations of the risk. Don't write code like this.
Reading data that isn't yours
Without isolation, a script can walk the whole document and collect whatever is visible or typed.
// Illustration only: code that reaches outside its own component.
const values = [];
document.querySelectorAll('input').forEach((el) => {
values.push(el.value);
});
// A hostile script could now send `values` to a server it controls.On a page showing contact details, a case comment, or a payment-related field, that loop would collect data the script's author was never meant to see.
Tampering with shared globals
Every script shares the same built-in objects, such as window, Array.prototype, and fetch. If one script replaces a built-in, every other script that uses it is affected.
// Illustration only: wrapping a shared global so every caller is observed.
const originalFetch = window.fetch;
window.fetch = function (...args) {
console.log('Observed request to', args[0]);
return originalFetch.apply(this, args);
};After this runs, every later fetch call on the page passes through the wrapper, including calls made by components from other vendors. The wrapper could log, alter, or drop requests. This technique is called monkey-patching. It's common and legitimate in some contexts, which is why it's hard to prevent without a boundary that gives each party its own copy of the globals.
Calling privileged APIs with the user's session
Code running in the page can call Salesforce endpoints, and the browser attaches the user's session to those requests. Unisolated code could make requests as the user that the user never intended. Platform-level checks still apply, such as field-level security and sharing on the server side. But a script could still read and write everything the user can, and the component author never agreed to that scope.
Interfering through naming and ordering
Not every problem is malicious. If two packages both define a global called window.config, the second load overwrites the first. If one library patches Date or JSON, others may break. Isolation also reduces these accidental conflicts, because each party works in its own environment.
Requirements for a solution
Given the problem, a browser-side isolation layer needs to meet four requirements:
- Separate parties from each other. Code from one source must not read or alter another source's DOM, data, or globals.
- Allow cooperation on purpose. Components still need to work together. The layer must offer sanctioned channels, so isolation doesn't make composition impossible.
- Stay compatible with real code. Developers rely on standard JavaScript and web APIs. If the layer broke those, nobody could build anything.
- Work without a rewrite of the platform. It must run in ordinary browsers, using features they already have.
These requirements pull against each other. Stronger separation tends to break more existing code. More compatibility tends to leave more gaps. The history of Salesforce's two approaches, Lightning Locker and Lightning Web Security, is a history of choosing different trade-offs between them. The comparison comes in a later chapter.
The shape of the solution
Salesforce draws the isolation boundary around the namespace. Instead of trying to separate every component from every other component, the platform separates code by who published it:
- Components in the same namespace are treated as one trust domain. They share an environment and can cooperate freely inside it.
- Components in different namespaces are separated from each other. They can't touch each other's DOM or globals.
- Communication across the boundary goes through the public contract of a component:
@apiproperties and custom events.
The platform also controls what the separated code can see of the browser itself. It does this by giving each namespace a controlled view of the built-in objects, which later chapters call a sandbox with distortions.
What this means for your code
You don't need to change how you write components to benefit from isolation. Following the supported patterns already keeps you inside the boundary. Compare the two ways of finding an input element:
import { LightningElement } from 'lwc';
export default class FocusInput extends LightningElement {
handleClick() {
// Supported: query only inside this component's own template.
const input = this.template.querySelector('lightning-input');
if (input) {
input.focus();
}
// Not supported as a way to reach your own markup:
// document.querySelector('lightning-input');
// That searches the page, which is the kind of reach isolation restricts.
}
}The first call stays inside your component's boundary and works under isolation. The commented-out call reaches into the page at large. Even where it appears to work in a given setup, it ties your component to markup it doesn't own.
The same idea applies to other components. When a child in another namespace needs to tell its parent something, it doesn't call into the parent. It dispatches an event.
import { LightningElement, api } from 'lwc';
export default class ItemPicker extends LightningElement {
@api label;
handleSelect() {
this.dispatchEvent(
new CustomEvent('select', { detail: { id: '001' } })
);
}
}The @api property and the event are the child's public contract. Everything else about the child is private, and isolation enforces that privacy at runtime across namespaces.
Where the rest of the tutorial goes
This chapter set up the problem and the requirements. The remaining chapters follow the concept graph:
- How namespaces become isolation boundaries, and how sandboxes and distortions change what code can do.
- How Lightning Locker and LWS compare, and how to enable LWS and migrate.
- What DOM access and standard web APIs look like under LWS.
- How components in different namespaces share data, and how to use third-party libraries from static resources.
- How Content Security Policy fits in, and how to troubleshoot errors.
Common misunderstandings
- "The same-origin policy already isolates components." It isolates origins. Components in a Lightning page share an origin, so the policy doesn't separate them.
- "Shadow DOM makes components secure from each other." It encapsulates structure and style for developers. It wasn't designed as a defense against hostile code.
- "Isolation only matters for third-party packages." It also matters for your own code. A bug or a compromised library in your org can expose your users' data in the same way.
- "If my code works in a sandbox test, it's safe." Passing under isolation shows you stayed inside the rules. It says nothing about whether your server-side logic enforces access correctly.
Exercise
Lightning Experience serves two components from different namespaces on the same record page. Both run on the same origin. Why doesn't the browser's same-origin policy keep one component from reading the other's data, and what do the two components use to communicate instead once an isolation layer is in place?
Show answer
The same-origin policy separates different origins. Both components' scripts load into one page on one origin, so the browser treats them as equally trusted and gives them the same privileges, including access to the same window, DOM, and globals. A separate isolation layer has to separate them by namespace. Once it does, the components communicate through the public contract of a component: @api properties set by the parent and custom events dispatched by the child.
Exercise
The snippet below runs inside a component. Name two risks it would create if there were no isolation between namespaces, and say what to use instead to reach elements in your own component. window.fetch = function () { / custom logic / }; const all = document.querySelectorAll('input');
Show answer
Replacing window.fetch changes a shared global, so every other component's network calls on the page would pass through your code, which could observe or alter them. Calling document.querySelectorAll('input') reads inputs across the whole page, including ones owned by other namespaces, so it could collect their values. To reach elements in your own component, use this.template.querySelector or this.template.querySelectorAll, which search only the component's own template.