2025-05-13 20:42:58

Lightning Message Channel in Salesforce

Salesforce Lightning Message Channel illustration showing a computer screen with code, speech bubbles, lightning bolt, and cloud icon on a blue background

A Lightning Message Channel is a communication mechanism provided by Salesforce that enables pub-sub (publish-subscribe) messaging across Lightning Web Components, Aura components, and Visualforce pages. It’s a powerful way to decouple components, allowing them to communicate without being directly connected in the component hierarchy.

Key Benefits of Using Lightning Message Channel

  • Decoupled Communication: Send and receive messages between components that don't have a direct parent-child relationship.
  • Cross-DOM Support: Communicate across different DOMs, including LWC, Aura, and Visualforce pages.
  • Improved Performance: Efficient and event-driven messaging enhances app performance and responsiveness.
  • Ease of Maintenance: Cleaner architecture with reduced inter-component dependencies.

How to Create and Use a Lightning Message Channel

1. Define the Message Channel Create a .xml file in the messageChannels directory in your Salesforce project.



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

 

2. Publish a Message Use the publish() method from lightning/messageService.



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

@wire(MessageContext)
messageContext;

publish(this.messageContext, SAMPLE_MESSAGE, {
    messageText: 'Hello from LWC!'
});

3. Subscribe to a Message



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

@wire(MessageContext)
messageContext;

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

handleMessage(message) {
    console.log('Received message:', message.messageText);
}

Example 

Imagine two LWC components, one displaying a list of accounts and the other displaying details of a selected account.

When the user selects an account from the list, the list component can publish a message to a message channel containing the account ID.

The details component can subscribe to this channel and update its display with the account details. 
 

1) Define the Message Channel

Located in: force-app/main/default/messageChannels/accountMessageChannel.messageChannel-meta.xml



<?xml version="1.0" encoding="UTF-8"?>
<LightningMessageChannel xmlns="http://soap.sforce.com/2006/04/metadata">
    <isExposed>true</isExposed>
    <lightningMessageFields>
        <description>Channel to pass selected Account Id</description>
        <fieldName>accountId</fieldName>
    </lightningMessageFields>
    <masterLabel>Account Message Channel</masterLabel>
</LightningMessageChannel>


2) Publish a message 

accountList.html:
 



<template>
    <lightning-card title="Account List">
        <template for:each={dummyAccounts} for:item="acc">
            <div key={acc.id} class="slds-m-around_x-small">
                <lightning-button label={acc.name} onclick={handleSelect} data-id={acc.id}></lightning-button>
            </div>
        </template>
    </lightning-card>
</template>

 accountList.js:
 



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

export default class AccountList extends LightningElement {
    @wire(MessageContext)
    messageContext;

    dummyAccounts = [
        { id: '001', name: 'Acme Corporation' },
        { id: '002', name: 'Global Media Inc.' },
        { id: '003', name: 'Sunshine Farms' }
    ];

    handleSelect(event) {
        const selectedId = event.target.dataset.id;
        publish(this.messageContext, ACCOUNTMC, { accountId: selectedId });
    }
}


3) Subscribe to a message

accountDetails.html:



<template>
    <lightning-card title="Account Details" if:true={account}>
         <p><strong>ID:</strong> {account.id}</p>
         <p><strong>Name:</strong> {account.name}</p>
         <p><strong>Industry:</strong> {account.industry}</p>
         <p><strong>Phone:</strong> {account.phone}</p>
    </lightning-card>
</template>


 accountDetails.js:



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

export default class AccountDetails extends LightningElement {
    account;
    dummyData = {
        '001': { id: '001', name: 'Acme Corporation', industry: 'Technology', phone: '123-456-7890' },
        '002': { id: '002', name: 'Global Media Inc.', industry: 'Media', phone: '987-654-3210' },
        '003': { id: '003', name: 'Sunshine Farms', industry: 'Agriculture', phone: '555-111-2222' }
    };
    
    @wire(MessageContext)
      messageContext;
      
      connectedCallback() {
      subscribe(this.messageContext, ACCOUNTMC, (message) => {
          this.account = this.dummyData[message.accountId];
      });
  }
}

 

Output:


 

Use Cases of Lightning Message Channel

  • 🔄 Syncing Components: Automatically refresh data in related components when one component updates it.

  • 🧭 Navigational Communication: Trigger page transitions or modals from remote components.

  • 📊 Dashboard Updates: Dynamically update dashboards or charts when filters change.

 

 

 

Get In Touch

Bring your business to life.


Get in touch with our expert Salesforce consultants to streamline your business processes and maximize efficiency.

What Happens Next :
    • 1We schedule a call at your convenience
    • 2We do a discovery and consulting meting
    • 3We prepare a proposal