LWC and Lightning Message Service (LMS)

Published by

on


Introduction

Lightning Message Service (LMS) is a powerful communication mechanism in Salesforce that enables cross-component communication between Lightning Web Components (LWC), Aura Components, and Visualforce Pages without requiring direct relationships.

When to Use LMS

  • To communicate between sibling LWC components that don’t share a parent-child relationship.
  • To enable communication between Aura and LWC components.
  • To exchange messages across different browser tabs or windows within a Salesforce app.

Setting Up Lightning Message Service

LMS requires the following steps:

  1. Create a Lightning Message Channel (LMS file in messageChannels folder).
  2. Publish messages from one component.
  3. Subscribe to messages in another component.

Step 1: Creating a Lightning Message Channel

The Lightning Message Channel (LMC) is defined in force-app/main/default/messageChannels/.

Create SampleMessageChannel.messageChannel-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningMessageChannel xmlns="http://soap.sforce.com/2006/04/metadata"
    fqn="SampleMessageChannel">
    <isExposed>true</isExposed>
    <lightningMessageFields>
        <fieldName>messageText</fieldName>
    </lightningMessageFields>
</LightningMessageChannel>

Explanation:

  • isExposed must be true to use it in LWC components.
  • lightningMessageFields defines the data structure of messages.

Step 2: Publishing a Message from an LWC Component

LWC JavaScript (messagePublisher.js)

import { LightningElement } from 'lwc';
import { publish, MessageContext } from 'lightning/messageService';
import SAMPLE_MESSAGE from '@salesforce/messageChannel/SampleMessageChannel__c';

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

    @wire(MessageContext)
    messageContext;

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

    handlePublish() {
        const message = { messageText: this.message };
        publish(this.messageContext, SAMPLE_MESSAGE, message);
    }
}

LWC HTML (messagePublisher.html)

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

Explanation:

  • Uses publish() to send data via SampleMessageChannel.
  • Sends a messageText field as part of the message payload.

Step 3: Subscribing to Messages in Another LWC Component

LWC JavaScript (messageSubscriber.js)

import { LightningElement, wire } from 'lwc';
import { subscribe, MessageContext } from 'lightning/messageService';
import SAMPLE_MESSAGE from '@salesforce/messageChannel/SampleMessageChannel__c';

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

    @wire(MessageContext)
    messageContext;

    connectedCallback() {
        subscribe(this.messageContext, SAMPLE_MESSAGE, (message) => {
            this.handleMessage(message);
        });
    }

    handleMessage(message) {
        this.receivedMessage = message ? message.messageText : 'No message received';
    }
}

LWC HTML (messageSubscriber.html)

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

Explanation:

  • Uses subscribe() to listen for messages on SampleMessageChannel.
  • Updates UI whenever a new message is received.

Using LMS Between Aura and LWC Components

LMS can also be used for communication between Aura Components and LWC Components.

Aura Component Publisher

Aura Component (AuraPublisher.cmp)

<aura:component>
    <lightning:messageChannel name="SampleMessageChannel__c" aura:id="messageChannel" />
    <lightning:button label="Send Message" onclick="{!c.publishMessage}" />
</aura:component>

Aura Controller (AuraPublisherController.js)

({
    publishMessage: function(component, event, helper) {
        var messageChannel = component.find("messageChannel");
        messageChannel.publish({ messageText: "Hello from Aura!" });
    }
})

This Aura component can send messages that the LWC Subscriber component can listen to, and vice versa.


Conclusion

  • LMS enables decoupled communication between LWC, Aura, and Visualforce pages.
  • Message Channels act as the transport mechanism.
  • Use publish() to send messages and subscribe() to receive messages.

In the next post, we will explore Deployment & Best Practices.

Stay tuned! 🚀