Sub topic 5
Enabling LWS in Your Org
This chapter covers turning Lightning Web Security (LWS) on, where the setting lives, what it affects, and how to roll it out without surprises. It assumes you can read basic LWC structure (template, class, metadata file), know what a namespace and a static resource are, and have read the earlier chapters on sandboxes, distortions, and the Locker comparison. You also need access to Setup in a sandbox, or an org where you are allowed to change session settings.
What the switch actually does
LWS is not a feature you add to a component. It is a runtime mode for the whole client. The mode decides which isolation engine wraps your code in the browser. Under Lightning Locker, each namespace's code is wrapped in secure object wrappers such as a secure window and secure document. Under LWS, each namespace runs in a JavaScript sandbox, and distortions adjust the behavior of specific APIs inside that sandbox.
When you flip the setting:
- Component source does not change. No redeploy is needed.
- The platform loads each component's code into a sandbox instead of wrapping it with Locker.
- The change applies to both Lightning web components and Aura components in the scope where it is enabled.
- Code that relied on Locker-specific behavior may behave differently. Code that Locker blocked may start working.
Because the switch changes runtime behavior and not source, you can't review the effect in a pull request. You find problems only by running the components.
Where the setting lives
LWS is controlled in two places, and they are independent. Mixing them up is a common source of confusion.
| Scope | Where to set it | What it affects |
|---|---|---|
| Salesforce org (Lightning Experience, Salesforce mobile app, Lightning apps) | Setup, Session Settings | Components running in the org's internal Lightning apps |
| Experience Cloud site | Experience Builder, Settings, Advanced | Components running on that one site |
The org-level setting does not turn LWS on for your Experience Cloud sites, and the reverse is also true. A team can run LWS in the internal org while a site still uses Locker, or the other way around. Treat each site as its own migration.
Enabling it at the org level
- In Setup, enter
Session Settingsin Quick Find and open it. - Find the option labeled for using Lightning Web Security for Lightning web components and Aura components.
- Select the checkbox.
- Save.
The label wording can change between releases, so search the page for "Lightning Web Security" if the exact text differs from what you see. Users pick up the change when their browser next loads Lightning resources. Ask testers to do a hard refresh, because cached component bundles can hide the change.
Enabling it on an Experience Cloud site
- In Setup, open Digital Experiences, then All Sites, and click Builder next to the site.
- In Experience Builder, open Settings, then Advanced.
- In the security section, choose Lightning Web Security instead of Lightning Locker.
- Publish the site so visitors get the new mode.
The site setting only takes effect on publish. If you test in preview and see no difference, check that you published.
Permissions and who should do it
Changing session settings needs an administrator profile, or a permission set with the right to customize the application. Because the setting changes how every component runs, treat it as a release event and not as a quick configuration tweak. Name an owner, announce a window, and keep the rollback step written down.
Rollback is simple. Clear the checkbox, or switch the site back to Lightning Locker and publish. Users get Locker again on their next load. This is why you can try LWS in production with a short test window. Even so, a sandbox rehearsal is the safer path.
A rollout path
The usual sequence has five stages, and each one answers a different question.
1. Inventory
List what runs in the scope you are about to change:
- Custom LWC and Aura components, grouped by namespace.
- Static resources loaded with
loadScriptorloadStyle. - Managed packages. You can't edit their code, so you depend on the vendor's LWS support. Check the vendor's release notes or ask them.
- Components that touch
document,window, global variables, or cross-component DOM queries.
The libraries and the cross-component DOM access are the most likely to fail, so find them first.
2. Enable in a sandbox
Use a full or partial copy sandbox if you have one, because it carries realistic data and the same installed packages. A developer sandbox works for a first pass, but the data and package differences can hide bugs.
3. Test
Test real user flows, not only that pages load. Load the pages that host your components and exercise the interactions: open dialogs, submit forms, render charts, upload files, and use any feature that calls browser APIs. Check the browser console on each page. Distortion and sandbox errors appear there.
4. Fix or replace
Failures usually fall into one of the categories you will see in the troubleshooting chapter: DOM access outside your template, a library that expects an unrestricted window, or a cross-namespace assumption. Decide whether to change your code, update the library, or drop it.
5. Enable in production
Pick a low-traffic window. After you flip the setting, run the same smoke tests against production and keep the rollback step ready.
A smoke-test component
A small diagnostic component lets you confirm the main behaviors in each environment without hand-testing every page. This one checks that your component can query its own template, that fetch to a same-origin path completes, and that a static resource library loads.
<!-- lwsSmokeTest.html -->
<template>
<lightning-card title="LWS smoke test">
<div class="slds-var-p-around_medium">
<lightning-input label="Test input"></lightning-input>
<lightning-button
label="Run checks"
onclick={runChecks}
></lightning-button>
<ul>
<template for:each={results} for:item="result">
<li key={result.name}>
{result.name}: {result.status}
</li>
</template>
</ul>
</div>
</lightning-card>
</template>// lwsSmokeTest.js
import { LightningElement } from 'lwc';
import { loadScript } from 'lightning/platformResourceLoader';
import CHART_JS from '@salesforce/resourceUrl/chartjs';
export default class LwsSmokeTest extends LightningElement {
results = [];
async runChecks() {
const results = [];
results.push(this.checkTemplateQuery());
results.push(await this.checkLibrary());
this.results = results;
}
checkTemplateQuery() {
try {
const input = this.template.querySelector('lightning-input');
return {
name: 'Template query',
status: input ? 'ok' : 'element not found'
};
} catch (error) {
return { name: 'Template query', status: `failed: ${error.message}` };
}
}
async checkLibrary() {
try {
await loadScript(this, CHART_JS);
const ok = typeof window.Chart === 'function';
return {
name: 'Static resource library',
status: ok ? 'ok' : 'loaded, but window.Chart is missing'
};
} catch (error) {
return {
name: 'Static resource library',
status: `failed: ${error.message}`
};
}
}
}<?xml version="1.0" encoding="UTF-8"?>
<!-- lwsSmokeTest.js-meta.xml -->
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>60.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>Adapt the static resource name (chartjs here) to a library you actually use. Add checks for each library or API pattern your inventory flagged. Run the component under Locker, enable LWS, and run it again. Any status that changes is worth investigating before users see it.
What to look for after enabling
Not every difference is a bug. Group what you see into three buckets.
| Observation | Likely cause | Action |
|---|---|---|
| Component renders and behaves as before | Code used only supported patterns | Nothing |
| Console error mentioning a blocked or distorted API | Code uses an API that LWS changes or restricts | Change the code, or use a supported alternative |
| Library throws on load or when run | Library expects unrestricted globals or DOM | Update the library, pick another, or isolate its use |
| Something that failed under Locker now works | LWS supports more standard APIs | Remove the workaround if you want, after testing |
| A managed package component breaks | Package not yet LWS-ready | Contact the vendor, hold the rollout for that scope |
Edge cases to plan for
- Per-scope differences. The org setting and each site setting are separate. After enabling at the org level, you still have to repeat the work for every Experience Cloud site that hosts your components.
- Mixed namespaces. Your own namespace, other namespaces, and installed packages each get their own sandbox under LWS. Anything that depended on reaching across namespaces by DOM traversal or shared globals should communicate through public
@apiproperties and custom events instead. - Caching. Browsers and the platform cache component bundles. Testers who report "nothing changed" often need a hard refresh or a fresh browser profile.
- Third-party scripts outside components. Scripts added by other means, such as site head markup, are not wrapped the same way as component code. Treat them as a separate check.
- Content Security Policy. LWS does not replace CSP. Both apply, so a script blocked by your trusted site list stays blocked after you enable LWS. The CSP chapter covers this.
- Jest tests. Local Jest tests do not run in the LWS sandbox, so a green unit-test suite says nothing about LWS behavior. You must test in a real org.
Checklist
- Confirm the current setting for the org and for each site before you start.
- Write down the owner, the window, and the rollback step.
- Inventory components, static resources, and managed packages.
- Enable in a sandbox, test real user flows, and read the browser console.
- Fix or replace what fails, then repeat the tests.
- Enable in production, repeat the smoke tests, and watch for user reports.
Exercise
Your company has one internal Lightning app and two Experience Cloud sites. An administrator enables LWS in Session Settings and reports that the migration is done. What is missing, and what should you do before calling it complete?
Show answer
The Session Settings option only covers the org's internal Lightning scope. Each Experience Cloud site has its own security setting in Experience Builder (Settings, Advanced) that must be switched to Lightning Web Security and then published. You should check the current mode of both sites, test them in a sandbox (or preview, then published) with real user flows, review the browser console for errors, and only then enable and publish them. Until then the sites still run whichever mode they had before, likely Locker.
Exercise
After enabling LWS in a sandbox, your unit tests in Jest all pass, but a chart component shows a blank canvas and the console reports an error from the charting library. Why didn't Jest catch this, and what is your next step?
Show answer
Jest runs components locally without the LWS sandbox or distortions, so it cannot reveal runtime isolation differences. The error occurs only in a real org. Next, reproduce it with the smoke-test approach (load the library with loadScript and check that the global exists), read the exact console message to see which API the library uses, then update or replace the library or change how it is used. If it can't be fixed quickly, switch back to Locker in that scope while you work on it.