Understanding Lightning Message Service (LMS) in Salesforce LWC

Understanding LMS in Salesforce LWC
Chinmaya By Chinmaya
8 Min Read

Introduction

Lightning Message Service (LMS) is a powerful feature in Salesforce that allows seamless communication between different components across the DOM in a Lightning Experience app.

It simplifies the process of sharing information between components, whether they are Lightning Web Components (LWC), Aura components, or even Visualforce pages.

Let’s dive into what LMS is, why it’s useful, and how to implement it with an example.

What is Lightning Message Service (LMS)?

Lightning Message Service (LMS) is a pub-sub (publish-subscribe) messaging framework that enables communication between Lightning Web Components (LWC) and Aura components.

It allows components to exchange data without being directly connected or having a parent-child relationship.
This is particularly useful in complex applications where components are spread across different parts of the page or even in different parts of the DOM.

Key features of LMS:

Why Use LMS?

    1. Simplifies Communication: Components don’t need to know about each other’s existence to share data.

    2. Cross-Domain Support: Supports communication between LWC, Aura, and Visualforce components.

    3. Better Performance: Reduces tightly coupled dependencies, improving the app’s scalability and performance.

    4. Centralized Communication: By using message channels, LMS provides a single source for managing interactions.

When to use Lightning Message Service?

Here are some situations when to use LMS:

    1. Cross-Component Communication: When you need components (LWC, Aura, or Visualforce) to communicate without being directly connected.
    2. Multiple Tabs or Apps: For sharing messages across different tabs or apps in the same Lightning Experience.
    3. Loose Coupling: When you want to reduce dependencies between components for better maintainability.
    4. Centralized Messaging: To manage communication through a single source (message channel) for consistency.
    5. Event Sharing: When traditional parent-child event propagation doesn’t fit your use case.

How LMS Works?

LMS follows the publish-subscribe pattern, which involves three main steps:

    1. Create a Message Channel: A message channel is like a topic or a channel where messages are published and subscribed to. It’s defined using an XML file in Salesforce.
    2. Publish a Message: A component can publish a message to a specific channel. This message can contain data that other components might need.
    3. Subscribe to a Message: Other components can subscribe to the same channel to receive the published messages and react accordingly.

Step-by-Step Implementation of LMS

Let’s walk through an example to understand how LMS works in practice.

Step 1: Create a Message Channel

First, you need to define a message channel.
A message channel is an XML file that defines the structure and namespace for messages.

    1. Go to File Explorer in your Salesforce project.

    2. Create a new file under force-app/main/default/messageChannel and name it exampleMessageChannel.messageChannel-meta.xml.

				
					<!-- exampleMessageChannel.messageChannel-meta.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<LightningMessageChannel xmlns="http://soap.sforce.com/2006/04/metadata">
    <masterLabel>ExampleMessageChannel</masterLabel>
    <description>This is an example message channel for LMS.</description>
    <isExposed>true</isExposed>
    <lightningMessageFields>
        <fieldName>messageData</fieldName>
        <description>This is the data payload.</description>
    </lightningMessageFields>
</LightningMessageChannel>
				
			
    • masterLabel: The name of the channel.

    • description: A brief description of the channel.

    • isExposed: Set to true to make the channel available for use.

    • lightningMessageFields: Define the fields that will carry the data in the message.

Save the file and deploy it to your org.

Step 2: Publish a Message

Next, let’s create a component that publishes a message to the channel.

PublisherComponent.js

				
					// publishComponent.js
import { LightningElement } from 'lwc';
import { publish, MessageContext } from 'lightning/messageService';
import EXAMPLE_MESSAGE_CHANNEL from '@salesforce/messageChannel/exampleMessageChannel__c';

export default class PublishComponent extends LightningElement {
    message = '';

    handleInputChange(event) {
        this.message = event.target.value;
    }

    handlePublish() {
        const payload = { messageData: this.message };
        publish(this.messageContext, EXAMPLE_MESSAGE_CHANNEL, payload);
    }
}
				
			
    • publish: This function is used to send a message to the channel.

    • MessageContext: Provides the context for the message service.

    • EXAMPLE_MESSAGE_CHANNEL: The message channel we created earlier.

PublisherComponent.html

				
					<template>
    <lightning-button label="Publish Message" onclick={handlePublish}></lightning-button>
</template>
				
			

Step 3: Subscribe to a Message

Now, let’s create another component that subscribes to the channel and reacts to the published message.

SubscriberComponent.js

				
					// subscribeComponent.js
import { LightningElement } from 'lwc';
import { subscribe, MessageContext } from 'lightning/messageService';
import EXAMPLE_MESSAGE_CHANNEL from '@salesforce/messageChannel/exampleMessageChannel__c';

export default class SubscribeComponent extends LightningElement {
    receivedMessage = '';

    connectedCallback() {
        this.subscribeToMessageChannel();
    }

    subscribeToMessageChannel() {
        this.subscription = subscribe(
            this.messageContext,
            EXAMPLE_MESSAGE_CHANNEL,
            (message) => {
                this.handleMessage(message);
            }
        );
    }

    handleMessage(message) {
        this.receivedMessage = message.messageData;
    }
}
				
			
    • subscribe: This function listens for messages on the channel.

    • connectedCallback: A lifecycle hook where we start the subscription.

    • handleMessage: A function to handle the received message.

SubscriberComponent.html

				
					<template>
    <p>Message Received: {messageReceived}</p>
</template>
				
			

Step 4: Use the Components in a Lightning Page

Finally, add both components to a Lightning page or app to see them in action.

				
					<!-- exampleApp.html -->
<template>
    <c-publish-component></c-publish-component>
    <c-subscribe-component></c-subscribe-component>
</template>
				
			

When you type a message in the publishComponent and click the publish button, the subscribeComponent will receive the message and display it.

How It Works in the Example?

    1. The PublisherComponent publishes a message when the button is clicked.

    2. The SubscriberComponent listens for the message and displays the content on the UI.

    3. Both components communicate using the SampleMessageChannel, without directly interacting with each other.

Real-World Use Cases for LMS

  1. Global Notifications: Send notifications from one component to multiple components across the application.

  2. Data Synchronization: Keep data in sync between components that are not directly related.

  3. Cross-Component Actions: Trigger actions in one component based on events in another component.

  4. Complex UIs: Manage communication in complex UIs where components are spread across different parts of the page.

Best Practices

    • Use Descriptive Channel Names: Name message channels clearly to reflect their purpose.

    • Unsubscribe When Not Needed: Always unsubscribe from channels when the component is disconnected to avoid memory leaks.

    • Minimize Message Size: Keep the messages lightweight for better performance.

    • Avoid Overuse: Use LMS only when components are truly independent; for tightly coupled components, consider direct communication.

    • Test Thoroughly: Test your LMS implementation to ensure messages are being sent and received as expected.

Conclusion

Lightning Message Service is a versatile tool for building modular and scalable Salesforce applications.

It simplifies communication between components, improves maintainability, and supports a variety of use cases.

By following the steps above, you can easily implement LMS in your Lightning applications and take advantage of its robust messaging capabilities.

Feel free to leave a comment if you have any questions or need further clarification. And don’t forget to share this post with your fellow Salesforce developers! 🚀

Share This Article
Follow:
Chinmaya is working as a Senior Consultant with a deep expertise in Salesforce. Holding multiple Salesforce certifications, he is dedicated to designing and implementing cutting-edge CRM solutions. As the creator of Writtee.com, Chinmaya shares his knowledge on educational and technological topics, helping others excel in Salesforce and related domains.
Leave a comment