Sub topic 2
What Lightning Message Service is and where it works
This chapter explains what Lightning Message Service (LMS) is, how it differs from the other ways components communicate, and which parts of Salesforce it supports. It stays at the working-model level. Later chapters cover channel metadata, publishing, subscribing, and scope in detail.
I assume you can already do the following:
- Build a basic Lightning web component (LWC) with a template, a JavaScript class, and decorators such as
@wire. - Use lifecycle hooks such as
connectedCallbackanddisconnectedCallback. - Work in a Salesforce DX project and deploy metadata.
- Place components on a Lightning page with the Lightning App Builder.
The gap LMS fills
LWC already gives you three ways to pass data between components:
- Public properties (
@api) pass data down from a parent to a child. - Custom DOM events pass data up from a child to a parent.
- A publish-subscribe module of your own, a plain JavaScript file that holds a list of callbacks, can connect components inside one LWC namespace.
The first two require the components to be in the same DOM tree, and the third only works for code that shares your JavaScript module and runs in the same page context. A Lightning page often breaks both assumptions. An administrator can drop a record list in the left column, a detail panel in the right column, and a utility-bar component in the footer. None of them is a parent or child of another. Some may be Aura components or Visualforce pages written years before your LWC.
LMS is the platform-supplied answer. It is a publish-subscribe service built into Lightning Experience. A component publishes a message to a named channel. Every component subscribed to that channel receives the message. Publisher and subscriber never reference each other. They only agree on the channel name and the shape of the message.
The working model
LMS has four moving parts.
| Part | What it is | Where it lives |
|---|---|---|
| Message channel | A metadata type (`LightningMessageChannel`) that names the channel and lists the fields a message can carry | Your org, deployed like any other metadata |
| Message context | An object that ties a component to the page's messaging system | Created per component, usually with `@wire(MessageContext)` |
| Publisher | Code that calls `publish` with a context, a channel, and a payload | Any supported component |
| Subscriber | Code that calls `subscribe` with a context, a channel, a handler, and optional scope | Any supported component |
The flow for one message looks like this:
Four properties of this model affect your design.
- The channel is the contract. The channel's metadata is the only thing both sides share. Neither side imports the other's code.
- Delivery is one-to-many and anonymous. The publisher gets no reply, no count of receivers, and no error if nobody is listening. A message published to a channel with zero subscribers is simply dropped.
- Messages are not stored. A component that subscribes after a message is published never sees that message. If the detail panel loads after the user selected a record, it needs another way to get the current state, such as a page reference or a wire adapter on the record id.
- Payloads are data, not behavior. A message carries serializable values such as strings, numbers, booleans, and plain objects. You cannot send a function or a DOM node through it.
The JavaScript surface
For LWC, everything comes from one module, lightning/messageService, plus a per-channel import:
import {
publish,
subscribe,
unsubscribe,
APPLICATION_SCOPE,
MessageContext
} from 'lightning/messageService';
import RECORD_SELECTED from '@salesforce/messageChannel/RecordSelected__c';The import path ends in __c, even though the metadata file names the channel RecordSelected. The __c suffix is how the platform exposes the channel to code. If you import RecordSelected without the suffix, the import fails to resolve. You will build the channel itself in the next chapters. For now, note that the module exports only five names:
publishsends a message.subscriberegisters a handler and returns a subscription object.unsubscribetakes that subscription object and stops delivery.MessageContextis the wire adapter that supplies the context.APPLICATION_SCOPEis a constant that widens delivery, covered in a later chapter.
The small surface is deliberate. LMS has no query language, no filters, and no message types beyond the channel itself. If you need to distinguish kinds of messages, you either create more channels or add a field to the payload.
Where LMS works
LMS spans component technologies, but only in certain containers. The table summarizes the common cases. Platform support changes between releases, so confirm edge cases in the current Salesforce documentation before you commit to a design.
| Environment | Can publish and subscribe? | Notes |
|---|---|---|
| Lightning web components in Lightning Experience | Yes | Use `lightning/messageService`. |
| Aura components in Lightning Experience | Yes | Use the `lightning:messageChannel` tag. |
| Visualforce pages in Lightning Experience | Yes | Use the `$MessageChannel` global and `sforce.one.publish` and `sforce.one.subscribe`. |
| Lightning console apps and the utility bar | Yes | Subscribers in other tabs and the utility bar can receive messages when they use `APPLICATION_SCOPE`. |
| Visualforce pages in Salesforce Classic | No | LMS is part of the Lightning Experience framework. |
| Salesforce mobile app | Limited or unsupported | Check the current documentation for your release. |
| Experience Cloud sites | Depends on the site type and release | Check the current documentation before relying on it. |
| Across browser tabs or windows | No | A message stays in the page where it was published. |
| Between a Lightning page and an external web app | No | Use platform events or an API instead. |
Two points are easy to miss. First, a Visualforce page can only use LMS when it is displayed inside Lightning Experience, for example embedded in a Lightning page or opened in a console tab. Opened on its own in Classic, it has no messaging context. Second, LMS works inside a single page load. A browser refresh clears all subscriptions and all in-flight state.
Who receives a message
By default, a subscriber receives messages only while its component is active, meaning visible in the page or in the selected tab of a console app. A background tab in a console app does not receive messages unless it subscribed with APPLICATION_SCOPE. This matters most in console apps and utility bars:
- Default scope limits delivery to the active area. Use it when you want a tab to react only to its own page.
APPLICATION_SCOPEdelivers messages to the subscriber even when it is not the active area. Use it when a utility bar item or another tab needs to react.
On a regular Lightning record or app page with no tabs, the two behave almost identically, because every component is in the active area. The difference only shows up in navigation containers. Scope gets its own chapter, so treat this section as a warning that a subscriber that works on a Lightning page can go silent when you move it into a console app.
LMS compared with the alternatives
LMS is not the answer to every communication problem. This table shows where it fits.
| Situation | Better choice | Reason |
|---|---|---|
| Child sends a value to its parent | Custom DOM event | The relationship already exists, and events are simpler and faster. |
| Parent sets data on a child | `@api` property | Direct, typed, and easy to trace. |
| Several components read the same record | `@wire` with `getRecord`, or Lightning Data Service | Each component reads the shared cache. No messages are needed. |
| Components in one namespace share state | A shared JavaScript module | Works in the same page context without a metadata deployment. |
| Unrelated components, any technology, same page | LMS | The only supported cross-technology client channel. |
| Notify other users or external systems | Platform events, Change Data Capture | These run on the server and reach other sessions. |
If you can solve the problem with an @api property or a custom event, do that first. LMS adds a metadata file, a deployment step, and a layer of indirection. That cost pays off only when the components truly are unrelated.
Common mistakes at this stage
- Expecting replay. A new subscriber does not receive earlier messages. Load initial state some other way.
- Using the wrong environment. Testing a Visualforce subscriber in Classic or in a standalone preview and concluding that LMS is broken.
- Forgetting that unsubscribed components still listen. Subscriptions created in
connectedCallbackstay active until you remove them. A later chapter covers the cleanup pattern. - Treating the channel like an API. Channels carry small notifications, not large datasets. Send an id and let the receiver fetch the record.
Exercise
A Lightning record page has a Visualforce page, an Aura component, and an LWC. The LWC should tell the other two when the user picks a record. A teammate suggests a custom DOM event because it needs no deployment. Why does that fail, and what should you use instead? Also name one case where LMS would still be the wrong choice.
Show answer
A custom DOM event only travels through the component tree, from a child to its ancestors, and the three components share no parent-child relationship. A Visualforce page also sits in an iframe, so the event never reaches it. Use LMS: deploy one message channel and have all three components subscribe to it, with the LWC publishing. LMS would be the wrong choice for notifying a user in a different browser session or an external system, because messages never leave the current page. Platform events or Change Data Capture fit that case.