Introduction to Lightning Message Service

Salesforce developers rejoice! There is now a standardized way to communicate between Lightning Web Components (LWC), Aura Components, and, yes, even Visualforce Pages. The new capability is called Lightning Message Service, LMS, for short. To help you understand how it works, I’d like to provide a basic example of how to use the service.

For an organization hesitant to migrate to Lightning Experience and its newer technologies, Aura Components and Lightning Web Components, LMS may make the migration palatable. With LMS’s ability to communicate between Visualforce pages and lighting components, you can take a more disciplined approach to upgrading. Instead of scrapping existing Visualforce pages and creating new Lightning components, you can update existing Visualforce pages to interact with new Lightning components to provide new functionality.

Lightning Message Service does have limitations, though. You cannot use LMS under the following conditions:

  • AppExchange
  • Salesforce Mobile
  • Communities

To some degree, LMS is like Application Events for Aura Components. With an Application Event, you define an Aura Event component that contains the fields that store the data passed as part of the event. You can then use it to pass events to components that have registered for the event. In LMS, the equivalent is a Message Channel, which is a new metadata type, not a component. It has tags that define the name and data fields for the event.

Message Channels

The first step is to create a Message Channel, most easily done using VS Code and the Salesforce CLI. The first step is to create a new folder, messageChannels, in the force-app/main/default folder. Within that folder, create a new file with “.messageChannel-meta.xml” as the extension. The contents of the file should be similar to the following:

<?xml version="1.0" encoding="UTF-8"?>
        <fieldName>messageText</fieldName>

<LightningMessageChannel xmlns="http://soap.sforce.com/2006/04/metadata">
    <masterLabel>SampleMessageChannel</masterLabel>
    <isExposed>true</isExposed>
    <lightningMessageFields>
        <description>Holds the message to display</description>
    </lightningMessageFields>
</LightningMessageChannel>

The masterLabel tag is followed by the name for the message channel; in this case, “SampleMessageChannel.” The lightningMessageField tag defines the fields that will carry the event payload. Use multiple lightningMessageField tags if you need more than one field in the event payload. The isExposed tags allow the channel to be used across namespaces.

Once the message channel file is complete, deploy it to your org. Now, you are ready to make use of the message channel.

Publishing to a Message Channel

For this blog, LWC’s will be used to demonstrate how to use LMS. The first component will be the “publisher.” In the component’s Javascript file, you will need to start by importing the elements needed from the lightning/messageService module and the previously defined messageChannel. For this example, we will need publish and MessageContext from the messageService.

import messageChannel from '@salesforce/messageChannel/Sample__c';
import {publish, MessageContext} from 'lightning/messageService'

After the imports, create the message context. You can accomplish this using the createMessageContext() method or, if the component extends LightningElement, by using the following syntax:

@wire(MessageContext)
    messageContext;

Now, set up is complete to publish to the Message Channel. All that is needed now is to make a call to “publish.”

publish(this.messageContext, messageChannel, message);

The publish method takes three arguments: the message context, the message channel, and the message itself. The message is an object that contains the fields defined in the Message Channel file.

let message = {messageText: 'This is a test'};

Publishing an event is that simple. Here is the full text of the publishing component. Note, in this example, the pressing of a button on the UI triggers the publishing.

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

export default class Publisher extends LightningElement {

    @wire(MessageContext)
    messageContext;

    handleButtonClick() {
        let message = {messageText: 'This is a test'};
        publish(this.messageContext, messageChannel, message);
    }
}

Subscribing to a Message Channel

Now let’s take a look at the receiving (subscriber) end. Like the publisher, the subscribing module needs to import the message channel and the appropriate elements of the message service, in this case: subscribe and MessageContext.

import messageChannel from '@salesforce/messageChannel/Sample__c';
import { subscribe, MessageContext } from 'lightning/messageService';

A message context is also required, just like in the publishing component.

@wire(MessageContext)
    messageContext;

Lastly, you need to create the subscription. The subscribe method that was imported is used for this purpose. It takes three arguments: the message context, the message channel, and callback to be executed when an event is received on the message channel.

this.subscription = subscribe(this.messageContext, messageChannel, (message) => {
            console.log(message.messageText);
        });

That’s it! These two components now communicate using LMS. Here is the full text of the subscribing component:

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

export default class Subscriber extends LightningElement {

    subscription = null;

    @wire(MessageContext)
    messageContext;

    connectedCallback() {
        this.handleSubscribe();
    }

    handleSubscribe() {
        if (this.subscription) {
            return;
        }
        this.subscription = subscribe(this.messageContext, messageChannel, (message) => {
            console.log(message.messageText);
        });
    }
    
}

Resources

  1. Documentation to use LMS with LWCs
  2. Documentation to use LMS with Aura Components
  3. An example implementation of VisualForce

Next Steps

Do you need help building and implementing components in your Salesforce solution or leveraging the platform to serve your business better? We’re happy to share how we can help. Contact our team today.

5 thoughts on “Introduction to Lightning Message Service”

  1. Oleksandr Tymchenko

    Hello, I have a problem. It’s work perfectly for admin logged user. But when I’m trying to see my page as a guest user, I see just an empty page and text “Invalid Page’

  2. Good morning Oleksandr, I need a little more context as to what you are trying to do. Is this page in a Community?

  3. Hi !
    When I created a message channel under its throwing error “cannot find the declaration of element ‘LightningMessageChannel’. But when I removed xmlns attribute in LightMessageChannel tag it’s not showing any error. I have modified even the package.xml file (in manifest folder).
    Can you please help me out

  4. Mag Pangilinan

    hello upon deployment of my new created messageChannel-meta.xml i am getting this error duplicate value found: duplicates value on record with id: im not sure why is this happening and how to resolve 🙁

  5. Mag Pangilinan

    hello, i am trying to deploy the messageChannel-meta.xml file in messageChannels folder but i am facing this error -> force-app\main\default\messageChannels\BoatMessageChannel.messageChannel-meta.xml duplicate value found: duplicates value on record with id: .

    i am currently stuck on this and not really sure how to resolve 🙁

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top