Start tracking your progress
Trailhead Home
Trailhead Home

Build Secure Apps with Lightning Web Components

Learning Objectives

After completing this unit, you’ll be able to:

  • Define Lightning Web Components (LWC).
  • Explain how LWC increases your application’s security.
  • Migrate from VisualForce or Aura to LWC.

Client-Side Security for Lightning Web Components (LWC)

Lightning Web Components (LWC) is Salesforce’s front-end JavaScript framework. Though Salesforce will continue to support Aura for the foreseeable future, LWC will eventually replace the Salesforce Aura Framework as the preferred user interface tool. LWC contains a large number of features from Aura, while its architecture is more akin to modern single-page application (SPA) frameworks, such as React or Vue. This means that while Aura and LWC serve the same purpose in the Salesforce developer ecosystem, LWC ships with modern security best practices inherited from SPA frameworks, like React and Vue. This means that when you build applications using LWC, you're getting up-to-date security built in by default. 

Client-side security is increasingly important as developers continue to build applications on top of the Salesforce Platform with more and more user interaction. It is imperative that, as a developer, you understand the built-in security mechanisms provided by LWC in addition to knowing how to write secure client-side code on top of the LWC framework. Doing so will help you prevent security vulnerabilities in your applications and provide a much better user experience. 

Security Features of LWC

Salesforce recommends LWC as the primary UI development framework for use on the Salesforce Platform for two reasons. First, LWC is secured with Locker by default, which prevents components from accessing the data and Document Object Model (DOM) of other components from other namespaces. This means that you don’t have to worry about one application leaking or accessing information from another. And second, LWC offers its own built-in security features, such as sanitization of malformed HTML code and blocking Content Security Policy (CSP)-incompatible code.

Locker

LWC uses Lightning Locker, a powerful security architecture for Lightning components that enhances security by isolating Lightning components in separate namespaces. Unlike frameworks that rely on iframes for isolation (like most similar products), Lightning Locker can be thought of as a JavaScript namespace isolation library. It operates by maintaining a list of sandboxes that are attached to specific namespaces and by preventing JavaScript execution that reaches beyond those sandboxes.

A man standing in front of a row of lockers labeled with separate namespaces.

Lightning Locker also promotes best practices that improve the security of an application by allowing access only to carefully audited APIs.

Security features in Lightning Locker include: 

  • JavaScript strict mode enforcement: Lightning Locker implicitly enables JavaScript strict mode. You don’t need to specify "use strict" in your code. JavaScript strict mode makes code more secure, robust, and supportable.
  • DOM access containment: A component can only traverse the DOM and access elements created by a component in the same namespace. This behavior prevents the anti-pattern from reaching into DOM elements owned by components in another namespace.
  • Secure wrappers: Restricts use of global objects by hiding an object or by wrapping it in a secure version of the object. For example, the secure version of the window object is SecureWindow. Locker intercepts calls to window and uses SecureWindow instead. Some methods and properties have different behavior or aren’t available on the secure objects.
  • eval() function limits: Use of the eval() function is supported to enable use of third-party libraries that evaluate code dynamically. However, it is limited to work only in the global scope of the namespace. The eval() function can’t access the local variables within the scope in which it’s called.
  • Analysis of MIME types: MIME types of files sent through the browser are analyzed. Locker permits some MIME types, sanitizes some, and blocks the rest.
  • Limited access to API framework: You can access published, supported JavaScript API framework methods only. These methods are published in the reference doc app at https://<myDomain>.lightning.force.com/auradocs/reference.app, where <myDomain> is the name of your custom Salesforce domain. Previously, unsupported methods were accessible, which exposed your code to the risk of breaking when unsupported methods were changed or removed.

LWC Security Best Practices

Load Assets Correctly

To import a third-party JavaScript or CSS library, use the platformResourceLoader module.

  1. Download the JavaScript or CSS files from the third-party library’s site.
  2. Upload the library to your Salesforce organization as a static resource, which is a Lightning security requirement.
  3. In a component's JavaScript file:
    1. Import the static resource. import myResourceName from '@salesforce/resourceUrl/myResourceName';
    2. Import methods from platformResourceLoader. import { loadStyle, loadScript } from 'lightning/platformResourceLoader';

Using the Lightning Platform resource loader guarantees your scripts always load in the correct order, are not duplicated, and load only when all dependencies have already loaded.
If the Lightning Platform resource loader is not used, it is possible that you or your customers may encounter page-breaking bugs as a result of a duplicated or improperly loaded script.

Properly Configure Event Propagation

After an event is fired, it can propagate up through the DOM. To understand where events can be handled, it is helpful to understand how they propagate.

Lightning web component events propagate according to the same rules as DOM events. The default configuration is bubbles: false and composed: false. This configuration prevents the event from bubbling up through the DOM and from crossing the shadow boundary. The only way to listen to this event is to add an event listener directly on the component that dispatches the event. This recommended configuration is the most secure because it carries the least amount of risk.

This configuration prevents the event from bubbling up through the DOM and from crossing the shadow boundary. The only way to listen to this event is to add an event listener directly on the component that dispatches the event. 

The Principle of Least Privilege

The principle of least privilege is the idea that any user, program, or process should have only the bare minimum privileges necessary to perform its function. Your components should have access only to the minimum required privileges and state required for proper functionality. This applies not only to the privileges and state on the client, but also in any Apex controllers and in any third-party integrations.

Secure by Default

When designing an API, the secure option should always be the default option—even at the cost of rapid development. This means that future developers will inherit the secure options built into the code.

Separation of Concerns

You should separate your concerns so that each LWC component you build has one specific task, rather than building monolithic components that have a large number of responsibilities. Imagine a monolithic LWC component photoGallery that has commenting, layouts, and photo display functionality all in one. This component could be broken down into more specific ones: photo, gridLayout, feedLayout, layoutManager, commentForm, commentList, commentContainer, and so on. Each iteration further increases the specificity of each component.

Properly Evaluate Third-Party Dependencies

Most JavaScript applications bring in a few third-party dependencies. It’s a good idea to evaluate third-party dependencies via manual review when possible. You can also use static analysis tooling, like Checkmarx, which make it easy to scan code for security problems. Likewise, a tool such as Snyk enables you to evaluate third-party dependencies against known vulnerability databases. 

Migrating to LWC

Migrating from Aura to LWC

Aura components and Lightning web components can exist in the same application. The programming model for Lightning Web Components is fundamentally different from the model for Aura components. Migrating a component is not a line-by-line conversion, and it’s a good opportunity to revisit your component’s design. 

The easiest components to migrate are simple components that only render UI. You get more gains in performance and developer productivity by migrating larger trees of components (components within components) rather than an individual component. However, it’s a useful learning experience to migrate one component and see how concepts in the Aura programming model map to concepts in the Lightning Web Components programming model.

After migrating one component, you’ll be in a better position to determine whether it makes sense for you and your org to:

  • Undertake a larger migration effort.
  • Use Lightning web components for new components only.
  • Stick with Aura components for now.

The choice is specific to you and may depend on your use cases and available resources. Whatever decision you make, migrating a component is a valuable learning exercise.

Resources