Sub topic 12
Troubleshooting LWS errors
This chapter assumes you know the basic structure of a Lightning web component, modern JavaScript (modules, async/await, classes), and how namespaces and static resources work in Salesforce. It builds on the earlier chapters about namespace sandboxes, distortions, DOM access, allowed APIs, third-party libraries, and Content Security Policy (CSP). The goal here is a repeatable way to find the cause of an LWS failure and to decide whether to change your code, change the library, or change a setting.
A working model for diagnosis
Almost every LWS failure comes from one of four causes:
- A distortion changed an API. LWS replaces or restricts a standard API inside your namespace's sandbox. Your code calls it the usual way and gets a different result or an error.
- A boundary was crossed. Code tried to reach DOM, objects, or globals owned by another namespace, or by the platform itself.
- A library assumed an unrestricted browser. Third-party code relied on a global, on
eval-style behavior, or on touching elements outside its own component. - A policy blocked a request. CSP, or a Trusted Sites setting, refused a script, style, image, or network call.
Name the cause first. Fixes follow from it, and guessing at fixes wastes time.
Step 1: Confirm that LWS is the cause
Before you read any LWS documentation, rule out ordinary bugs. A component that throws Cannot read properties of null may have a plain timing problem, such as querying an element before it renders.
A reliable test is to compare behavior with LWS on and off. Use a sandbox org or a scratch org, and change the session setting in Setup so that the component runs under Lightning Locker or no extra layer. The exact setting name is in the Session Settings page. Note that turning the setting off in production affects every user, so do this only in a non-production org.
- If the failure disappears with LWS off, LWS is involved. Continue to step 2.
- If the failure remains, it is an ordinary bug. Debug it as usual.
- If it fails differently under Locker than under LWS, record both messages. The difference often points at the exact distortion.
Step 2: Read the error carefully
Open the browser developer tools and look at the Console and Network tabs. Check three things.
- The message text. LWS and CSP messages usually name the blocked operation or the blocked URL.
- The stack trace. Look for the first frame that belongs to your code or to your library. Frames from the platform tell you less.
- Whether the failure happens at load or at use. A failure while loading a static resource points at the library or at CSP. A failure when a user clicks points at your handler.
Use a debug-friendly mode so you see readable stack traces. Salesforce offers a Debug Mode setting for users, which serves unminified framework code. It is slow, so enable it only for the user you are testing with.
Common failures and their fixes
The table links typical symptoms to causes. Use it as a starting point, not a complete list.
| Symptom | Likely cause | Typical fix |
|---|---|---|
| `querySelector` returns `null` for an element you can see on the page | You queried `document` instead of `this.template`, or the element belongs to another component | Query with `this.template.querySelector` after render |
| Selecting an element inside a child component returns nothing | The child's internals are not part of your template | Expose an `@api` method or property on the child |
| Library throws on load with a "not defined" error | The library expects a global that is not present in your sandbox | Check how it attaches to `window` and what it needs |
| Library loads but nothing draws | It writes to elements outside your component | Pass it an element from your own template |
| Request to an external host fails | CSP or Trusted Sites blocks the origin | Add the host as a trusted site |
| A property you set on another component's object is ignored | Cross-namespace access is wrapped or restricted | Use public properties and custom events |
DOM queries that return null
The most frequent report is an element that exists on screen but cannot be found. The fix is almost always to scope the query to your own template.
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();
}
}
}Two points about this pattern. First, this.template.querySelector finds elements your template declares. It does not reach into the shadow content of child components, and it should not. Second, the if (input) guard hides a real problem if the query is wrong. During debugging, log a message in the else branch so you see the miss.
If the element is rendered conditionally, the query only works after the render that creates it. Run it in renderedCallback, or in a handler that fires after the render.
Cross-namespace access that fails
When your component needs something from a component in another namespace, do not search for its elements or read its globals. Those objects are protected by namespace isolation, so you may see a wrapped object, a missing property, or an error. Use the public contract instead.
// 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' } })
);
}
}The parent passes label through the template and listens for select. Keep the event detail to plain data such as strings, numbers, and simple objects. Passing complex objects across a boundary can produce wrapped copies that do not behave like the originals.
Third-party libraries that fail
A library that worked under Locker or in a plain browser page can fail under LWS. The usual reasons are that it reaches for globals, queries document directly, or uses features that CSP forbids. The next example loads a library and makes any failure visible.
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);
}
}
}The libraryLoaded flag stops a second load when renderedCallback runs again. The try/catch separates two failure types, which you can tell apart by the message:
- A failure inside
loadScriptmeans the file did not load or did not run. Check the static resource name, the file path, and CSP. - A failure at
new window.Chartmeans the library ran but could not attach, or was not exposed onwindowthe way you expected.
To decide between changing your code and changing the library, apply these questions in order:
- Does the library offer a mode that accepts an element you pass in, instead of finding elements by selector? Use it.
- Is there a newer version that documents support for Lightning Web Security? Upgrade.
- Can you wrap the library so that it only touches elements from your own template? Do that.
- If none of these work, replace the library. Patching minified vendor code makes later upgrades painful.
Policy failures: CSP and Trusted Sites
If the Network tab shows a request that never leaves the browser, or the Console shows a CSP violation, the cause is policy, not the sandbox. Adding code will not help.
- For a blocked script, style, or image source, check where the file is hosted. Files in static resources are allowed. Files from other hosts are not, unless you configure the host.
- For a blocked API call, check the host against your Trusted Sites list, and confirm which directive (for example
connect-src) the entry covers. - Inline scripts and code built from strings are the usual targets of CSP. Move such code into a file in a static resource.
A policy fix is a setting change. It is a security decision, so involve the person who owns your org's security configuration before you add a host.
Errors that appear only after migration
After you move from Locker to LWS, some old workarounds fail. Check for these:
- Code that depended on Locker's wrapper objects, such as checks on object types that Locker had altered.
- Workarounds that bypassed Locker's rules and now conflict with LWS rules.
- Libraries that you had patched or replaced to suit Locker.
Remove the workaround, test with the original library, and keep the change only if it fails. Fewer workarounds means fewer surprises later.
A debugging checklist
- Reproduce the failure in a sandbox or scratch org.
- Test with LWS on and off to confirm the cause.
- Read the Console and Network tabs and find the first frame in your code.
- Classify the failure: distortion, boundary, library assumption, or policy.
- Apply the smallest fix for that class.
- Retest, and remove debug logging that you no longer need.
Exercise
A component calls document.querySelector('.chart-area') to find a div in its own template. It returns null under LWS, even though the div is visible. What is the likely cause, and what change fixes it?
Show answer
The query runs against document, which does not reach into the component's shadow content. Change it to this.template.querySelector('.chart-area'), and run it after the element renders, for example in renderedCallback.
Exercise
A third-party library loads without error, but a call to new window.Chart(...) throws. The Network tab shows the file loaded with status 200. Which class of failure is this, and what are your next two steps?
Show answer
The file loaded, so it is not a policy failure. It is a library assumption or sandbox problem, because the library ran but did not expose or attach what you expected. Next, log error from the catch block and check what the library put on window in the console. Then check whether the library accepts an element you pass in, and look for a version that documents LWS support.
Exercise
A request to https://api.example.com fails in the browser, and the Console shows a CSP violation for connect-src. Should you change the component code?
Show answer
No. This is a policy failure. Add the host to the Trusted Sites list for the correct directive, after the org's security owner approves it. Component code changes will not fix a blocked origin.