What is the Lightning Message Service (LMS), and when should you use it for cross-component communication?
Answer
Basics: When two components are siblings, unrelated, or built with different frameworks, events and properties cannot connect them. LMS gives them a shared named channel: one publishes a message, any subscriber on the page receives it. Typical examples: a filter panel updating a results list, or a selector driving a detail view.
How it works:
- Create
force-app/main/default/messageChannels/RecordSelected.messageChannel-meta.xmlwithisExposedtrue and the field names allowed in the payload. - In LWC, import the channel (
@salesforce/messageChannel/RecordSelected__c) pluspublish,subscribe,unsubscribe,MessageContext,APPLICATION_SCOPEfromlightning/messageService. - Get context with
@wire(MessageContext) messageContext;. - Publisher:
publish(this.messageContext, CHANNEL, { recordId }). - Subscriber: in
connectedCallbackcallsubscribe(this.messageContext, CHANNEL, msg => ..., { scope: APPLICATION_SCOPE }); indisconnectedCallbackcallunsubscribe. - Aura uses
lightning:messageChannel; Visualforce usessforce.onestyle$MessageChannelreferences.
Advanced / deep dive: By default a subscriber only receives messages while its component is active (for example the visible tab); APPLICATION_SCOPE receives them even when not active. Messages are JSON-serializable; do not send functions or large payloads, send ids and let receivers fetch data. LMS works within one browser tab or window; it cannot talk across tabs or windows, and it is not for server push, where and platform events apply. Experience Cloud support depends on the site type and framework, so verify in current release notes. Compared with a pub/sub JavaScript module, LMS is supported, crosses framework boundaries and respects Lightning page lifecycle. Compared with bubbling events it avoids tight coupling, but it creates implicit global dependencies, so name channels by business concept and document payloads. Container-based communication (events and ) remains better when a parent-child relationship exists.