Sub topic 3
Message channels as the shared contract
This chapter assumes you can write a basic Lightning web component (LWC). It also assumes you have seen a Salesforce DX project layout and know what the @wire decorator does. The previous chapters covered why parent-child events don't reach unrelated components, and what Lightning Message Service (LMS) is. This chapter covers the one piece every LMS setup shares: the message channel.
What a message channel is
A message channel is a piece of Salesforce metadata that gives a communication path a name. Components never send messages to each other directly. A publisher sends a message to a channel, and every active subscriber to that channel receives it.
The publisher and the subscriber don't import each other, and neither knows the other exists. They only agree on three things:
- The name of the channel.
- The names of the fields that a message carries.
- What each field means.
This agreement is the contract. The channel is the only thing the two sides have in common.
In metadata terms, a message channel is a LightningMessageChannel component. It lives in your org and deploys with the rest of your project, like an Apex class or a custom object.
The diagram shows why the pattern works for unrelated components. Adding a fourth subscriber changes nothing for the publishers. Neither side holds a reference to the other.
The contract has two halves
A channel contract has a formal half and an informal half.
The formal half is the metadata file. It fixes the channel's API name and lists the fields a message is supposed to carry. Every component refers to the channel by that name, so a typo produces an error at build or load time instead of silent misbehavior.
The informal half is the meaning of the fields. The file can hold a description for each field, and you should write one. The platform can't tell you whether recordId holds a 15-character or an 18-character ID, or whether source is a component name or a page name. Those conventions live in the descriptions and in your team's habits.
Anatomy of the metadata file
Here is a channel with two fields.
<?xml version="1.0" encoding="UTF-8"?>
<LightningMessageChannel xmlns="http://soap.sforce.com/2006/04/metadata" fqn="RecordSelected">
<description>Published when a user selects a record in a list.</description>
<isExposed>true</isExposed>
<lightningMessageFields>
<description>Id of the selected record</description>
<fieldName>recordId</fieldName>
</lightningMessageFields>
<lightningMessageFields>
<description>API name of the object that the record belongs to</description>
<fieldName>objectApiName</fieldName>
</lightningMessageFields>
<masterLabel>Record Selected</masterLabel>
</LightningMessageChannel>Save it as force-app/main/default/messageChannels/RecordSelected.messageChannel-meta.xml. The folder name and the file suffix both matter. The folder must be messageChannels, and the suffix must be .messageChannel-meta.xml. If either is wrong, the deploy won't treat the file as a channel.
| Element | Purpose |
|---|---|
| `fqn` | The channel's API name, set as an attribute on the root element. It must match the file name before `.messageChannel-meta.xml`. |
| `description` | A sentence that says when the channel is used. Other developers read this first. |
| `isExposed` | Controls whether the channel can be used from outside its own namespace. |
| `lightningMessageFields` | One block per field. Repeat the block for each field. |
| `fieldName` | The property name that a message carries. |
| `masterLabel` | The label shown in Setup and in tooling. |
The name of the channel
The fqn value is the API name, and the same rules apply as for other metadata names. Use letters, numbers, and underscores. Start with a letter. Avoid double underscores and don't end the name with an underscore. Pick a name that describes the event, such as RecordSelected or FilterChanged. Avoid names that describe a place, such as SidebarChannel, because the channel may later serve components that have nothing to do with the sidebar.
The `__c` suffix
The __c suffix is the detail that catches most people. In the metadata file the name is RecordSelected. Everywhere else, the name has __c appended, just as with custom objects and fields:
import RECORD_SELECTED from '@salesforce/messageChannel/RecordSelected__c';In an Aura component, the type attribute is also RecordSelected__c. In Visualforce, the expression is {!$MessageChannel.RecordSelected__c}. If the channel belongs to a namespaced package, the namespace comes first, as in myns__RecordSelected__c.
If you import RecordSelected without the suffix, the module can't be resolved. The component then fails to compile or load.
The `isExposed` setting
Set isExposed to true if components in other namespaces need to use the channel. This applies, for example, if you ship the channel in a managed package and customers write their own subscribers. For components in your own namespace, the value isn't what makes the channel reachable. Most examples set it to true, and it's a reasonable default for a channel you want others to build on. Set it to false when the channel is an internal detail of a package.
What the import gives you
The import @salesforce/messageChannel/RecordSelected__c returns a reference to the channel. You pass that reference to publish, subscribe, and unsubscribe. You don't call methods on it, and you don't read the field list from it.
This means the field list is not visible to your JavaScript. No autocomplete tells you which properties a message has. The metadata file is the reference, so read it before you write code against a channel.
A common pattern is to import the channel once, at the top of each component, and give it an upper-case constant name that describes the event:
import { LightningElement, wire } from 'lwc';
import { publish, MessageContext } from 'lightning/messageService';
import RECORD_SELECTED from '@salesforce/messageChannel/RecordSelected__c';
export default class RecordList extends LightningElement {
@wire(MessageContext)
messageContext;
handleSelect(event) {
const payload = {
recordId: event.currentTarget.dataset.id,
objectApiName: 'Account'
};
publish(this.messageContext, RECORD_SELECTED, payload);
}
}Both fields in the payload match the names in the metadata file. The next chapters explain MessageContext, publish, and subscribe in detail. For now, notice that the channel constant is the only link between this component and any subscriber.
How strictly the contract is enforced
Treat the field list as documentation first. Don't count on the platform to reject a message that has a missing field, an extra field, or a value of the wrong type. A subscriber should handle the message defensively:
handleMessage(message) {
if (!message || !message.recordId) {
return;
}
this.selectedId = message.recordId;
}A check like this costs little and protects you when a second publisher appears with a slightly different idea of the contract. If you need strict guarantees, add them in your own code. Check required fields in the subscriber, and keep the publisher's payload in one helper function so that all publishers build it the same way.
Changing a channel after release
Changing a channel affects every component that uses it, so change it with care.
- Adding a field is the safe change. Existing subscribers ignore properties they don't read.
- Renaming or removing a field breaks subscribers that read it. They don't throw an error. They see
undefinedand behave as if no value was sent. - Changing what a field means, for example switching from a record ID to a record name, is the worst case. Nothing fails, and the data is simply wrong.
- Renaming the channel breaks every import. If the channel is in a released managed package, you can't rename it at all.
When you must make a breaking change, create a new channel such as RecordSelectedV2, move publishers and subscribers over, and retire the old channel later. Both channels can exist side by side during the move.
Granularity: one channel or many
Decide how many channels you need by asking what a subscriber should be able to ignore.
A subscriber receives every message on the channels it subscribes to. It can't filter by field on the platform side. If one channel carries "record selected", "filter changed", and "tab closed" events, every subscriber must inspect each message and discard the ones it doesn't want. This is easy to get wrong.
A better rule is one channel per kind of event, with one clear meaning. Split a channel when subscribers need different subsets of its messages. Merge channels only when their messages always travel together and always mean the same thing.
Checklist for a new channel
- Name the event, not the screen. Use a short API name such as
RecordSelected. - Write a
descriptionfor the channel and for every field. - Keep fields to the minimum a subscriber needs. An ID is usually better than a whole record.
- Set
isExposedbased on whether other namespaces will use the channel. - Save the file in
messageChannelswith the.messageChannel-meta.xmlsuffix. - Import it everywhere with the
__csuffix.
Exercise
A teammate saves a channel file as force-app/main/default/messageChannels/FilterChanged.messageChannel-meta.xml with fqn="FilterChanged". In an LWC, they write import FILTER_CHANGED from '@salesforce/messageChannel/FilterChanged'; and the component fails to load. What is wrong, and what should the import be?
Show answer
The import is missing the __c suffix. Components refer to a channel by its API name with __c appended, so the import should be import FILTER_CHANGED from '@salesforce/messageChannel/FilterChanged__c';. The metadata file itself is correct, because the fqn has no suffix.
Exercise
A published channel has the field recordId. A developer wants to rename it to selectedRecordId for clarity and edits the metadata file. Existing subscribers read message.recordId. What happens to them, and what is a safer approach?
Show answer
Subscribers don't raise an error. They read undefined from message.recordId and behave as if no record was selected. A safer approach is to add selectedRecordId while keeping recordId during a transition period, or to create a new channel such as RecordSelectedV2, move publishers and subscribers to it, and then retire the old channel.