Sub topic 6
Publishing a Message from an LWC
This chapter covers the publisher side of Lightning Message Service (LMS). You will write a component that publishes a message, learn what each argument to publish does, and see the errors people hit most often.
It assumes you know the basics of Lightning Web Components (templates, JavaScript classes, decorators such as @wire), the connectedCallback and disconnectedCallback lifecycle hooks, and how to deploy metadata with a Salesforce DX project. It also assumes you have already created the RecordSelected message channel from the earlier chapter and obtained a MessageContext.
What publishing does
Publishing sends one message, a plain JavaScript object, to a named message channel. LMS delivers it to every active subscriber of that channel that is in range. The publisher does not know who the subscribers are, how many there are, or whether there are any. If nobody is subscribed, the call succeeds and the message is dropped.
LMS is a notification mechanism, not a store. It does not queue messages for components that load later, and it does not keep the last value. A component that subscribes after a message was published never sees that message.
The three pieces you need
A publisher needs three things.
- The
publishfunction, imported fromlightning/messageService. - A
MessageContext, which tells LMS where the publisher lives on the page. - The message channel, imported from
@salesforce/messageChannel.
The channel import
The import path uses the channel's API name. The metadata file you deployed has fqn="RecordSelected". In JavaScript you refer to it with the __c suffix:
import RECORD_SELECTED from '@salesforce/messageChannel/RecordSelected__c';The suffix is required. If your channel belongs to a managed package, the namespace goes in front, for example @salesforce/messageChannel/myns__RecordSelected__c. The imported value is a reference that publish and subscribe understand. It is not an object you read fields from.
The MessageContext
MessageContext is a wire adapter. You wire it to a property, and LMS fills in an object that identifies your component's place in the page.
@wire(MessageContext)
messageContext;The value is provisioned asynchronously. For most event handlers this does not matter, because the user clicks long after the wire has resolved. It matters if you call publish inside connectedCallback. At that moment this.messageContext is usually still undefined. The next section shows how to deal with that.
A complete publisher
This component renders a list of records. Clicking one publishes its Id.
<template>
<lightning-card title="Records" icon-name="standard:account">
<ul class="slds-var-p-around_small">
<template for:each={records} for:item="record">
<li key={record.Id}>
<a href="#" data-id={record.Id} onclick={handleSelect}>
{record.Name}
</a>
</li>
</template>
</ul>
</lightning-card>
</template>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 {
records = [
{ Id: '001000000000001AAA', Name: 'Acme' },
{ Id: '001000000000002AAA', Name: 'Globex' }
];
@wire(MessageContext)
messageContext;
handleSelect(event) {
event.preventDefault();
const payload = { recordId: event.currentTarget.dataset.id };
publish(this.messageContext, RECORD_SELECTED, payload);
}
}Points worth noting:
event.currentTargetis the element that has the handler, here the<a>.event.targetcould be a child element, which would not have thedata-idattribute.event.preventDefault()stops thehref="#"link from changing the URL.- The hard-coded
recordsarray keeps the example self-contained. In a real component you would load them with an Apex method or@wire. - The key in the payload,
recordId, matches thefieldNamedeclared in the channel metadata.
The component needs a meta file so you can place it on a page:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>60.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>The publish signature
publish(messageContext, messageChannel, message);| Argument | Type | Purpose |
|---|---|---|
| `messageContext` | Object from `@wire(MessageContext)` | Identifies the publisher's location, which LMS uses for scope decisions |
| `messageChannel` | Import from `@salesforce/messageChannel` | Names the channel to publish on |
| `message` | Plain object | The payload delivered to subscribers |
publish returns nothing. There is no acknowledgment, no list of recipients, and no return value you can use to check delivery. Delivery to subscribers is also not something the publisher can wait on. Do not write code that depends on a subscriber having finished its work after publish returns.
Publishing at the right time
Publishing from a user event handler is the safest case. Problems appear when you publish from lifecycle hooks or wire callbacks.
Publishing on load
Suppose a component should announce its default selection when it loads. This version fails:
connectedCallback() {
// messageContext is not ready yet
publish(this.messageContext, RECORD_SELECTED, { recordId: this.defaultId });
}this.messageContext has not been provisioned when connectedCallback runs, so the call fails. A reliable alternative is to publish from a place that only runs once the context exists. A simple pattern is to guard on the context and publish from the handler of another wire:
import { LightningElement, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
import { publish, MessageContext } from 'lightning/messageService';
import RECORD_SELECTED from '@salesforce/messageChannel/RecordSelected__c';
export default class DefaultAnnouncer extends LightningElement {
@wire(MessageContext)
messageContext;
@wire(getRecord, { recordId: '$recordId', fields: ['Account.Name'] })
wiredRecord({ data }) {
if (data && this.messageContext) {
publish(this.messageContext, RECORD_SELECTED, { recordId: data.id });
}
}
}This example has its own limit. If the record wire resolves before the context does, the guard skips the publish and nothing retries it. Wire adapters generally resolve in the order they are declared, but you should not rely on that. If you must publish at load, prefer a user action. Otherwise, also publish from a second place (for example renderedCallback with a flag) once both values are present.
Also remember that subscribers may not exist yet when you publish on load. A message sent while the subscriber is still loading is lost.
Publishing repeatedly
If a user types into a search box and you publish on every keystroke, each subscriber's handler runs on every keystroke. Publish on a meaningful event (a selection, a blur, a button click), or debounce:
handleInput(event) {
const value = event.target.value;
window.clearTimeout(this.timer);
this.timer = window.setTimeout(() => {
publish(this.messageContext, SEARCH_CHANGED, { term: value });
}, 300);
}This assumes a SearchChanged channel imported as SEARCH_CHANGED. Clear the timer in disconnectedCallback so a removed component does not publish later.
What happens to the payload
LMS passes the message to subscribers. Keep these rules in mind:
- Send data that can be serialized: strings, numbers, booleans, plain objects, and arrays of those. Do not send functions, DOM nodes, or class instances.
- Do not rely on a subscriber being able to change your object. Treat a published payload as read-only, and copy it before you change it.
- Do not publish a reactive proxy you own and later mutate. Build a fresh object for each call, as
handleSelectdoes. - Keys that are not declared as fields in the channel metadata are not an error at publish time, but other subscribers (especially Aura and Visualforce ones) expect the documented fields. Stick to them.
Chapter on payload design covers this in more depth. For publishing, the short rule is to send identifiers and small values, and let subscribers fetch what they need.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Deployment of the component fails on import | Channel is not deployed to the org, or the name is wrong | Deploy the `.messageChannel-meta.xml` file first and check the name |
| Import fails with a "module not found" style error | Missing `__c` suffix in the import path | Use `@salesforce/messageChannel/RecordSelected__c` |
| `publish` throws or does nothing on load | `messageContext` not yet provisioned | Publish from a user event, or guard on the context |
| Subscriber never receives the message | Subscriber is outside the publisher's scope, or subscribed after the publish | Check scope settings on the subscriber, and check load order |
| Subscriber receives `undefined` for a field | Payload key does not match the channel's `fieldName` | Align the key with the metadata |
| Handler runs many times for one action | Several subscriptions exist for one component | Subscribe once and unsubscribe on disconnect |
Verifying that publishing works
You can check a publisher without writing a subscriber first. Add a throwaway subscriber that logs, or use a Jest test. With Jest, the @salesforce/sfdx-lwc-jest package ships a stub for lightning/messageService, and you can mock publish:
import { createElement } from 'lwc';
import RecordList from 'c/recordList';
import { publish, MessageContext } from 'lightning/messageService';
import RECORD_SELECTED from '@salesforce/messageChannel/RecordSelected__c';
describe('c-record-list', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.clearAllMocks();
});
it('publishes the selected record Id', () => {
const element = createElement('c-record-list', { is: RecordList });
document.body.appendChild(element);
const link = element.shadowRoot.querySelector('a');
link.click();
expect(publish).toHaveBeenCalledWith(
expect.anything(),
RECORD_SELECTED,
{ recordId: '001000000000001AAA' }
);
});
});The jest stub makes publish a mock function, so you can assert on its arguments. MessageContext is imported to show that the stub provides it; the component still wires it itself. In the browser, you can also open the developer tools and watch the subscriber's log output to confirm delivery.
Summary of rules
- Import
publishandMessageContextfromlightning/messageService, and the channel with the__csuffix. - Wire
MessageContextonce per component and pass it to everypublishcall. - Send a fresh, small, serializable object that uses the channel's declared field names.
- Publish from user events where you can. Treat load-time publishing as a special case.
- Expect no reply. The publisher cannot see who received the message.
Exercise
A developer calls publish(this.messageContext, RECORD_SELECTED, payload) inside connectedCallback, and it fails. Explain why, and give two ways to restructure the code.
Show answer
@wire(MessageContext) is provisioned asynchronously, so this.messageContext is usually still undefined when connectedCallback runs. Two fixes: (1) move the publish call into a user event handler such as a click, which runs after the wire has resolved; (2) guard on this.messageContext and publish from a later hook or wire handler (for example renderedCallback with a flag) once the context exists. Remember that subscribers may also not be loaded yet, so a load-time message can still be missed.
Exercise
Your channel metadata file has fqn="OrderPlaced". Write the import statement for it in a Lightning web component, and say what happens if there are no subscribers when you call publish.
Show answer
import ORDER_PLACED from '@salesforce/messageChannel/OrderPlaced__c'; The __c suffix is required. If there are no subscribers, the publish call still succeeds and the message is dropped. LMS does not queue or replay messages for later subscribers.
Exercise
A search box component publishes on every keystroke and the page slows down. What change reduces the load, and what cleanup should the component do when it is removed?
Show answer
Debounce the publish, for example with setTimeout and clearTimeout and a delay of about 300 ms, or publish only on a meaningful event such as Enter or blur. In disconnectedCallback, clear any pending timer so that a removed component does not publish afterward.