Sub topic 8
Sharing Data Across Namespaces with Public Properties and Events
This chapter covers how components from different namespaces exchange data under Lightning Web Security (LWS). It assumes you can build a basic Lightning web component (template, class, metadata file) and use @api, CustomEvent, and async/await. It also assumes you know that a namespace identifies a package or org, and that LWS isolates code by namespace, as covered in the earlier chapters of this tutorial.
Why namespaces change how you share data
LWS gives each namespace its own JavaScript sandbox. Code in acme and code in c (the default namespace of your org) run in separate sandboxes. Each sandbox has its own view of globals, and LWS applies distortions to the APIs that code can call.
In practice, two components in different namespaces cannot share state by agreeing on a global name. Suppose a component in namespace acme sets window.sharedCart = {...}. A component in c should not expect to read it. Each sandbox has its own global environment, so the value is not visible across the boundary.
Components also cannot reach into each other's DOM. A component can query only its own template, and the DOM that belongs to another namespace is off limits.
Salesforce supports two channels between components, and both work across namespaces:
- Public properties (
@api) carry data down, from parent to child. - Custom events carry data up, from child to parent.
Both are part of the normal LWC component contract. Because they are explicit, LWS does not need to treat them as a security exception.
Public properties: data going down
A child exposes a public property with @api. The parent sets it in its template, as in label="Pick an item", or from JavaScript on the child element.
Rules that matter across namespaces:
- Only members decorated with
@apiare visible to other components. Everything else on the class is private, and a component in another namespace can't get at it. - A parent should treat the child's public API as its entire contract. Do not reach for
this.template.querySelector('acme-item-picker').someInternalField. Even when the parent could technically find the element, only@apimembers are supported. - Values that a parent passes into a child through a public property are read-only inside the child. LWC enforces this for objects and arrays. If the child needs to change the data, it copies the value first and sends the change back to the parent in an event.
- Prefer plain data: strings, numbers, booleans, arrays, and plain objects. Avoid passing class instances, DOM nodes, or functions.
The last point deserves explanation. When an object crosses a sandbox boundary, LWS keeps the two sides separated. The receiving side may see a wrapped version of the object instead of the original. You may find that identity checks such as === on an object that made a round trip do not behave as they would inside one namespace, and that methods or prototype checks like instanceof may not match. If your design only needs the values inside an object, this does not matter. If it depends on the object being the same instance, redesign it.
Custom events: data going up
A child announces something by dispatching a CustomEvent. The parent listens with an on<eventname> attribute in its template or with addEventListener.
Guidelines for events that cross namespaces:
- Put your data in
detail, and keepdetaila plain, serializable object. Prefer primitives and simple objects. - Name the event in lowercase with no spaces or hyphens. A name such as
itemselectedis safer than one that collides with a native event. - Do not make assumptions about
event.target. Event retargeting means the parent usually sees the child host element, not elements inside the child's template. - Do not mutate
event.detailafter dispatching it. Treat it as immutable. - Use
bubblesandcomposedonly when you really need them. A direct parent-child relationship does not need either. Wider propagation makes the event harder to reason about, and listeners in a different namespace can observe it.
A complete parent and child example
The child is the one from the topic plan. It has one public property and one event.
// child component (any namespace), for example acme/itemPicker
import { LightningElement, api } from 'lwc';
export default class ItemPicker extends LightningElement {
@api label;
handleSelect() {
this.dispatchEvent(
new CustomEvent('select', { detail: { id: '001' } })
);
}
}The child needs a template that triggers handleSelect:
<template>
<lightning-button label={label} onclick={handleSelect}></lightning-button>
</template>The parent lives in a different namespace, for example c. It puts the child in its template, sets the public property, and handles the event:
<template>
<acme-item-picker label="Pick an item" onselect={handleSelect}></acme-item-picker>
<p>Selected id: {selectedId}</p>
</template>import { LightningElement } from 'lwc';
export default class PickerHost extends LightningElement {
selectedId;
handleSelect(event) {
// Read plain values out of detail. Do not mutate detail.
this.selectedId = event.detail.id;
}
}The parent never touches the child's internals. It sets label, listens for select, and reads event.detail.id. This code works the same way whether the two components are in one namespace or two.
What crosses the boundary and what does not
The table summarizes what to expect when data moves between namespaces.
| Item | Safe to pass? | Notes |
|---|---|---|
| Strings, numbers, booleans | Yes | No special concerns. |
| Plain objects and arrays | Yes | The receiver sees them as read-only for `@api` values. Copy before editing. |
| Class instances | Avoid | Prototypes and `instanceof` checks may not match across sandboxes. |
| DOM nodes or elements | No | Another namespace's DOM is not yours to reach into. |
| Functions as callbacks | Avoid | Use events instead. A callback runs in its owner's sandbox and can behave unexpectedly. |
| Values stored on `window` | No | Each namespace sandbox has its own globals. |
Patterns that fail, and what to do instead
Reaching into the other component's DOM
A parent in c might try this.template.querySelector('acme-item-picker').shadowRoot.querySelector('input'). This fails or returns nothing, because the other component's template is encapsulated. Expose a method on the child instead:
import { LightningElement, api } from 'lwc';
export default class ItemPicker extends LightningElement {
@api
focus() {
const input = this.template.querySelector('lightning-input');
if (input) {
input.focus();
}
}
}The parent calls picker.focus(). The child does the DOM work inside its own template, which is allowed.
Using globals as a message bus
Code like window.appState = { user } in one namespace and window.appState.user in another is a common source of "undefined" errors after enabling LWS. Replace it with a property or event if the components are related. If they are not, see the next section.
Passing a function and expecting shared state
A parent may pass a callback to a child's @api property so the child can report back. It can work, but the function crosses the boundary and executes in a different sandbox from its caller. Events are the supported route for child-to-parent communication, so prefer them. They also make the direction of data flow obvious when you read the template.
Components that are not parent and child
Public properties and events need a containment relationship in the DOM. For components that sit in different parts of a page, for example a utility bar component and a record page component, use Lightning Message Service (LMS). You define a message channel and components publish and subscribe to it. LMS works across LWC, Aura, and Visualforce, and it does not depend on shared globals. Use the same discipline as with events: send plain data, and keep the payload small.
Debugging cross-namespace data problems
When data does not arrive, check these in order:
- Is the property decorated with
@apiin the child? Without it the parent's value is silently ignored or throws, depending on how it is set. - Does the event name match?
onselectin the template listens forselect. A capital letter in the event name or the handler attribute is a frequent mistake. - Is the event leaving the child at all? A child that dispatches from an inner element and does not set
bubblesandcomposedwill not reach a distant ancestor. - Is the value the right kind? If you are comparing objects with
===after a round trip, compare fields instead. - Does the code depend on a global? Search for
window.usage and replace it with one of the channels above. - What does the browser console say? Errors that mention a sandbox, a distortion, or an access denied on an object usually point to a value or API that crossed a namespace boundary in an unsupported way.
Summary of the design rules
- Treat every namespace boundary as an API boundary.
- Send data down with
@apiproperties and up with custom events. - Keep payloads plain: primitives, arrays, and simple objects.
- Never rely on shared globals, shared object identity, or another component's DOM.
- Expose behavior as
@apimethods instead of reaching into a child.
Exercise
A component in namespace c stores the current user's choice with window.selectedItem = id. A component from the managed package namespace acme on the same page reads window.selectedItem and gets undefined after LWS is enabled. Explain why, and describe two ways to fix it, one for a parent-child layout and one for components that are not related in the DOM.
Show answer
Under LWS each namespace runs in its own sandbox with its own global environment, so a property set on window by c is not visible to acme. For a parent-child layout, have the child dispatch a CustomEvent whose detail holds the id, and have the parent handle it and pass the value to the other component through an @api property. For unrelated components, publish the id on a Lightning Message Service channel and subscribe in the other component. In both fixes only plain data crosses the namespace boundary.
Exercise
A child component in namespace acme has @api items, an array of objects. The child code runs this.items.push({ id: 'x' }) and throws an error. Why does this happen, and how should the child add an item?
Show answer
Values passed into a child through @api are read-only in the child. To add an item, the child copies the array, for example const next = [...this.items, { id: 'x' }], and uses the copy locally or dispatches a CustomEvent with the new array in detail so the parent owns the change and passes the updated array back down.