Sub topic 11
Migrating from Locker to LWS
This chapter assumes you know the basic Lightning web component file structure, modern JavaScript (modules, async/await), and how static resources and namespaces work. It also assumes you have read the earlier chapters on namespace isolation, sandboxes and distortions, and the Locker and LWS comparison. Here you will turn that knowledge into a migration plan: what to check, in what order, and how to decide between changing code and changing a library.
What a migration actually changes
Lightning Locker and Lightning Web Security (LWS) are both client-side isolation architectures. Your component source does not change shape when you move between them. The same HTML template, the same JavaScript class and the same metadata file run under either one.
What changes is the environment around your code:
- Under Locker, your code touches secure wrapper objects such as
SecureElementandSecureWindow. These wrappers stand in for the real browser objects. - Under LWS, your code touches the real browser objects. A per-namespace sandbox applies distortions to selected APIs.
This means migration problems fall into a few predictable groups:
- Code that worked around Locker's wrappers and now has no reason to.
- Code or libraries that Locker blocked and LWS now permits.
- Code that depended on behavior that LWS distorts differently.
- Libraries that were never tested against either model.
Most orgs find that more code works after enabling LWS, not less. Failures still happen, so you migrate in a sandbox first.
Step 1: Inventory what you have
Before you change any setting, list the code that is most likely to be affected. Not every component carries the same risk.
| Code | Risk | Why |
|---|---|---|
| Components that only use `this.template`, `@api`, and standard events | Low | They use the supported patterns from the DOM access chapter. |
| Components that call `loadScript` or `loadStyle` | High | Third-party libraries make their own assumptions about `window` and `document`. |
| Components that reach outside their template with `document.querySelector` | Medium | Queries are scoped by namespace and may return fewer elements than you expect. |
| Aura components | Medium | LWS covers Aura as well, so the same org-wide setting applies to them. |
| Components that share objects across namespaces | Medium | Objects from another namespace's sandbox may be distorted or wrapped differently. |
| Code with Locker-specific workarounds | Medium | The workaround may now be unnecessary or even harmful. |
Search your source for these markers:
loadScript,loadStyle, and@salesforce/resourceUrlimports.document.andwindow.references outsiderenderedCallbacksetup code.- Comments that mention Locker,
SecureElement, or "workaround". instanceofchecks against DOM types, which behave differently when wrappers are involved.JSON.stringifyorstructuredClonecalls on objects that came from another component.
Write down which namespace each component and each static resource belongs to. Most surprises come from code and libraries living in different namespaces than the author assumed.
Step 2: Enable LWS in a sandbox
LWS is an org-level setting. You turn it on in Setup under Session Settings by selecting the option for Lightning Web Security for Lightning web components and Aura components. The exact wording of the label can shift between releases, so search Setup for "Session Settings" and read the option's help text.
Follow this order:
- Use a sandbox that holds a recent copy of your production components and static resources. A scratch org with only a few test components will not expose real problems.
- Enable the setting and save.
- Hard-refresh your browser. Cached component bundles from before the change can mask or distort test results.
- Open the browser developer tools console before loading any page, so you catch errors that fire at load time.
Two scope details matter:
- The setting applies to the whole org, not to individual components. You cannot run half your components under Locker and half under LWS in the same org. This is why the sandbox rehearsal matters.
- Experience Cloud sites have their own security setting in Experience Builder. Check each site you run and enable LWS there as well. Test sites separately from the internal Lightning Experience, because guest users and external users reach different data and sometimes different components.
Step 3: Remove Locker workarounds
Teams often wrote defensive code to survive Locker's wrappers. Some of that code can be deleted. Some of it must stay. Review each workaround and ask whether the original problem still exists.
A common case is a component that avoided a library feature by copying data into plain objects. Another is a component that wrapped DOM access in several fallbacks. Under LWS, the simple supported pattern is enough:
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 pattern works under both Locker and LWS, so it is the model to move toward. If you find code that gets elements through document.querySelector or window.document, replace it with this.template.querySelector where the element is in your own template. That change is safe before and after migration, so you can ship it ahead of enabling LWS.
Be careful in the other direction. Do not remove a check just because it looks like a Locker workaround. Feature detection that guards against missing APIs also protects you against browser differences, and it costs little.
Step 4: Test third-party libraries
Libraries are the most common source of migration failures. A library loaded with loadScript runs in the same namespace sandbox as your component, so it sees the same distorted window and document.
The pattern to follow is the one from the library chapter: load once, wrap in try/catch, and report failures.
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);
}
}
}For each library, check the following:
- It loads. The
loadScriptpromise resolves and the global it defines exists onwindow. - It initializes. Calling its constructor against your template element does not throw.
- It renders and responds. Click handlers, resize behavior, tooltips and exports all work, not only the first paint.
- It works across namespaces. If a managed package and your own code both load the same library, each namespace gets its own copy and its own sandbox. A library instance created in one namespace should not be handed to another.
When a library fails, you have three options. Decide in this order:
- Upgrade to a newer version of the library. Many libraries have fixed assumptions about globals since Locker days.
- Change how you call it, for example by passing the element reference from
this.templateinstead of letting the library search the whole document. - Replace it with a library or a base Lightning component that does the same job.
Patching a minified library file in the static resource is the option of last resort. You then own every future upgrade.
Step 5: Check cross-namespace communication
Components in different namespaces live in different sandboxes. Passing a live object between them can produce surprising results, because each side may see a distorted version of it. The safe contract is the one from the cross-namespace chapter: public @api properties for inputs and custom events for outputs, with plain serializable data.
// 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' } })
);
}
}During testing, verify these points for every parent and child pair that crosses a namespace boundary:
- The
detailof each event holds only strings, numbers, booleans, arrays, and plain objects. - No component stores a reference to another namespace's DOM element and uses it later.
- Public properties receive data, not functions or class instances that depend on a specific sandbox.
If a pair breaks, fix the data shape at the boundary instead of adding workarounds inside either component.
Step 6: Check Content Security Policy interactions
LWS does not replace Content Security Policy (CSP). A script or request that CSP blocks is still blocked after migration. When a test shows a network error, read the console message carefully to see whether it names a CSP directive or a sandbox restriction, because the fix differs. A CSP error means you need a Trusted URL or a different resource location. A sandbox error means you need to change how the code runs.
Step 7: Roll out and keep a way back
Once the sandbox passes, plan the production change.
- Pick a low-traffic window and tell support teams in advance.
- Enable LWS in production and have testers open the main apps immediately, with the console open.
- Watch for user reports and for errors in your own logging for the first few days.
- If a critical component breaks and you cannot fix it quickly, you can switch the org setting back. Treat that as an emergency step, since it affects every component at once.
Keep a short record of what you changed: libraries upgraded, workarounds removed, and any component that needed a code fix. This record helps the next release cycle, because later updates can reintroduce edge cases.
Common migration mistakes
- Testing only in Lightning Experience. Experience Cloud sites, Salesforce mobile, and embedded contexts can behave differently. Test each place your components appear.
- Forgetting to refresh caches. Stale bundles make a passing test meaningless.
- Blaming LWS for every error. Some failures predate migration, such as a missing static resource or a wrong resource path. Compare the error with the same page under Locker.
- Changing many things at once. If you upgrade libraries, remove workarounds, and enable LWS in one step, you cannot tell which change broke what. Ship code cleanups first, then flip the setting.
- Leaving unused workarounds in place. Dead compatibility code makes later debugging harder. Remove it once the migration is stable.
Summary
Migration is a staged process: inventory, sandbox test, cleanup, library validation, boundary checks, and a monitored rollout. LWS usually accepts more code than Locker did, so the work concentrates on third-party libraries and cross-namespace data. Treat each failure as a decision between changing your code and changing the library, and start with the smaller change.
Exercise
Your org runs a custom component that loads a charting library with loadScript. After you enable LWS in a sandbox, the chart does not draw, and the console shows an error from inside the library file. List the first three things you would do, in order.
Show answer
First, confirm the failure is new by checking the same page with LWS off in another sandbox or a copy, so you know the migration caused it. Second, check the library version and upgrade to the latest release, then retest, since many errors come from old assumptions about globals. Third, if it still fails, change how the component calls the library, for example by passing the canvas element from this.template.querySelector instead of letting the library search the document. Replace the library only if those steps fail, and patch its source only as a last resort.
Exercise
A parent component in your namespace passes a class instance to a child component from a managed package through a public property. It worked under Locker but behaves oddly under LWS. What change fixes the design?
Show answer
Stop sharing a live object across the namespace boundary. Pass plain serializable data (strings, numbers, booleans, arrays, plain objects) through public @api properties, and return results through custom events whose detail holds plain data. Each namespace then rebuilds any class instances it needs inside its own sandbox.