Sub topic 4
Creating and deploying a message channel
A message channel is a piece of Salesforce metadata. Publishers and subscribers both refer to it, so it has to exist in the org before any component can use it. This chapter covers how to write the file, where it goes in a project, how to deploy it, and the errors you will probably hit.
This chapter assumes you know the following:
- The structure of a Salesforce DX project.
- How to authorize an org with the Salesforce CLI.
- How to deploy metadata with the CLI.
- That Lightning Message Service (LMS) connects components that have no parent-child relationship.
What a message channel is, in file terms
The previous chapter described the channel as the shared contract. In a project, that contract is one XML file. It has no code, no behavior, and no handler logic. It declares a name, a label, and optionally the fields that messages on that channel are expected to carry.
A channel is a different kind of thing from a Lightning web component bundle or an Apex class. You cannot create it from the Setup UI or the Developer Console. You create it as a file in a source-format project and deploy it with the Metadata API, either through the CLI or through a package.
File location and naming
Message channels live in a messageChannels folder under your package directory. The file name has this form:
force-app/main/default/messageChannels/RecordSelected.messageChannel-meta.xmlThree parts of the name matter:
messageChannelsis the folder name the CLI expects for this metadata type.RecordSelectedis the channel's API name. It must match thefqnattribute inside the file..messageChannel-meta.xmlis the required suffix.
If the folder or suffix is wrong, the CLI will not recognize the file as a channel. Depending on your CLI version, it may skip the file without an error or report a metadata-type problem.
Anatomy of the channel file
This is the channel used throughout the tutorial.
<?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>
<masterLabel>Record Selected</masterLabel>
</LightningMessageChannel>| Element | Purpose |
|---|---|
| `fqn` (attribute) | The channel's API name. It must match the file name before `.messageChannel-meta.xml`. Use letters, numbers, and underscores, starting with a letter, as you would for other API names. |
| `masterLabel` | A human-readable label shown in tooling. |
| `description` | Explains when the channel is used. Write it for the next developer who has to decide whether to publish on it. |
| `isExposed` | Controls whether the channel can be used outside its own namespace. It matters mainly for managed packages. In an org with no namespace, you can usually leave it out. |
| `lightningMessageFields` | Zero or more entries naming the fields a message carries. Each has a `fieldName` and a `description`. |
Message fields are documentation
The lightningMessageFields entries describe the payload, but you should not treat them as enforced validation. A publisher passes a plain JavaScript object, and a subscriber reads whatever properties it expects. Do not count on Salesforce to reject a payload that has extra or missing properties. Keep the field list accurate so it works as the written contract, and validate in your own code where it matters. Payload design is covered in its own chapter.
You can declare several fields by repeating the element:
<lightningMessageFields>
<description>Id of the selected record</description>
<fieldName>recordId</fieldName>
</lightningMessageFields>
<lightningMessageFields>
<description>API name of the object, for example Account</description>
<fieldName>objectApiName</fieldName>
</lightningMessageFields>The `__c` suffix
The name changes between the file and the code. The file uses RecordSelected. Components import RecordSelected__c. Salesforce adds the __c suffix, as it does for custom objects and fields.
import RECORD_SELECTED from '@salesforce/messageChannel/RecordSelected__c';The @salesforce/messageChannel/ scoped module gives you a value that identifies the channel. You pass that value to publish and subscribe in later chapters.
If the channel belongs to a managed package with a namespace, the import includes the namespace: @salesforce/messageChannel/myns__RecordSelected__c. The isExposed setting is relevant when components in a different namespace need to use that channel.
Deploying the channel
The following diagram shows the path from source file to a component that can use the channel.
Deploy with the Salesforce CLI
The simplest deploy sends only the channel folder:
sf project deploy start --source-dir force-app/main/default/messageChannelsYou can also deploy one channel by metadata name:
sf project deploy start --metadata LightningMessageChannel:RecordSelectedIf you run sf project deploy start with no arguments in a scratch org project, the CLI deploys all changed source. In a sandbox or production org, it deploys everything listed in the project. In both cases the channel is included if its file is in a package directory listed in sfdx-project.json.
Deploy the channel before the components
The org must already contain the channel when a component that imports it is saved. If you deploy the publisher first, the deployment fails because @salesforce/messageChannel/RecordSelected__c cannot be resolved. A single deploy that contains the channel and its components works. The platform resolves dependencies inside one deployment. When you split work across several deployments, deploy the channel first.
Using a manifest
If your team deploys with a package.xml manifest, the metadata type name is LightningMessageChannel:
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
<types>
<members>RecordSelected</members>
<name>LightningMessageChannel</name>
</types>
<types>
<members>*</members>
<name>LightningComponentBundle</name>
</types>
<version>60.0</version>
</Package>Deploy it with:
sf project deploy start --manifest manifest/package.xmlThe members list uses the channel name without __c and without the file suffix. Use an API version that your org supports. The 60.0 shown here is an example.
Retrieving an existing channel
If a channel already exists in the org, for example one created by another team, pull it into your project:
sf project retrieve start --metadata LightningMessageChannel:RecordSelectedRetrieve before you edit. Changing a channel only in your local copy and deploying it overwrites the org's version.
Changing a channel after components use it
Adding a field to lightningMessageFields is safe. Existing publishers and subscribers keep working, because fields are not enforced.
Renaming or removing a channel is different. Every component that imports RecordSelected__c must change at the same time. Dependent components can also block a delete, so plan a rename as three steps:
- Create the new channel.
- Change all publishers and subscribers to import it.
- Delete the old channel once nothing references it.
Renaming the fqn in a file does not rename the channel in the org. It deploys a new channel with the new name and leaves the old one in place.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Deploy output does not list the channel | The file is in the wrong folder or has the wrong suffix | Move it to `messageChannels/` and use `.messageChannel-meta.xml` |
| A component fails to save with an unresolved module for the channel | The channel is not in the org yet, or the import omits `__c` | Deploy the channel first, and import `RecordSelected__c` |
| Deploy error that the `fqn` and the file name do not agree | The `fqn` attribute differs from the file name | Make them identical, including capitalization |
| Messages are never received, with no error | The publisher and subscriber import different channel names, or a subscriber is not active | Compare both import lines. Later chapters cover subscription and scope |
| A channel from a managed package cannot be used | The package author did not set `isExposed` to `true` | Ask the package owner to expose it |
Checking that the channel exists
After a deploy, confirm the channel is in the org before debugging component code. One way is to retrieve it back into a scratch folder:
sf project retrieve start --metadata LightningMessageChannel:RecordSelected --output-dir retrievedIf the command returns the file, the channel is deployed. If it reports no results, the deploy did not include it. Check the folder, the suffix, and your sfdx-project.json package directories.
Exercise
A teammate saves a file named Record_Selected.messageChannel-meta.xml whose root element has fqn="RecordSelected". What happens on deploy, and what import line would a component use once the file is corrected so that both names are RecordSelected?
Show answer
The deploy fails because the fqn must match the file name before .messageChannel-meta.xml. Here the file name uses Record_Selected and the fqn uses RecordSelected. After both are changed to RecordSelected and the file is deployed, the component imports import RECORD_SELECTED from '@salesforce/messageChannel/RecordSelected__c';. The __c suffix is added to the name in the import.
Exercise
You deployed a publisher component and a new channel in two separate deployments, publisher first. The first deployment failed. Why, and what is the safest order?
Show answer
The publisher imports @salesforce/messageChannel/RecordSelected__c, and the org did not yet contain the channel, so the module could not be resolved. Deploy the channel first, or put the channel and the components in the same deployment so the platform resolves the dependency.