What is Lightning Web Security (LWS) and how does it enhance security compared to legacy LockerService?
Answer
Basics: Components from different namespaces run on the same page, so they must not read or tamper with each other's data or the DOM. Locker enforced this by wrapping objects in "Secure" proxies, which broke many standard APIs and third-party libraries. LWS instead evaluates each namespace's code in its own sandbox and "distorts" a small set of APIs that would be unsafe, leaving the rest of the web platform behaving normally.
How it works: Enable it in Setup > Session Settings by selecting "Use Lightning Web Security for Lightning web components and Aura components" (new orgs may have it on by default; verify in current release notes). The runtime creates an isolated sandbox per namespace, and code accesses window, document, Object and so on through those sandboxes. Cross-namespace access to another sandbox's objects is blocked by default, and LWS applies a defined set of API distortions for security.
Advanced / deep dive: Comparison: Locker used SecureWindow, SecureElement and similar wrappers, so instanceof, equality and library detection often failed; LWS uses native objects inside the sandbox, so most libraries (charts, utilities) work unmodified. Performance is better because there is no heavy proxying. Both enforce Content Security Policy, which still limits where scripts and styles can load from (use static resources or CSP Trusted Sites). Components in the same namespace share a sandbox, which is why unmanaged c namespace code can share state, while managed-package namespaces stay isolated from each other. Trusted Mode and API-version-specific behaviors differ from Locker, so test third-party libraries after switching; LWS also has documented distortions and a console/Trusted Sites configuration for exceptions. Salesforce has been migrating orgs and communities toward LWS; check the current release notes for Locker retirement timing.
Setup steps rather than code: