Sub topic 10
Designing message payloads
This chapter assumes you can already create a message channel, publish with publish and MessageContext, and subscribe in a Lightning web component. Here the focus is on what goes inside the message: which fields to include, what types are safe, and how to keep a channel stable as more components depend on it.
Why payload design matters
A message channel is a shared contract. The publisher and every subscriber agree on the channel name and on the shape of the payload. Nothing in the platform enforces that shape at runtime. The fields listed in the channel metadata are documentation. A publisher can send any object, and a subscriber receives whatever arrives.
This means a poorly designed payload fails quietly. A misspelled field name gives undefined in the subscriber. A field that one publisher fills and another leaves out leads to subscribers that work on one page and break on another. Payload design is how you prevent those failures.
What a payload is
The payload is the third argument to publish. It is a plain JavaScript object.
const payload = {
recordId: '001xx000003DGbYAAW',
source: 'accountList'
};
publish(this.messageContext, RECORD_SELECTED, payload);The subscriber receives that object as the argument to its handler.
handleMessage(message) {
this.selectedId = message.recordId;
}The next table lists what is safe to put in a payload.
| Value | Safe to send? | Notes |
|---|---|---|
| String, number, boolean | Yes | Preferred for most fields |
| `null` | Yes | Use it to mean "nothing selected" |
| Plain object | Yes | Keep it shallow |
| Array of primitives or plain objects | Yes | Keep it short |
| Function | No | Not serializable, so it is not delivered |
| DOM element or component reference | No | Ties subscribers to the publisher's internals |
| Class instance with methods | Avoid | Subscribers see data, not behavior |
| `Date` object | Avoid | Send an ISO 8601 string instead |
The platform does not accept functions or other values that cannot be serialized. Treat the payload as data that could be written to JSON and read back, and your code stays inside the supported behavior.
Send identifiers, not whole records
The most useful rule is to send a reference to the data, not the data itself. The first payload below is small and stable. The second duplicates a record.
// Preferred
{ recordId: '001xx000003DGbYAAW' }
// Avoid
{
record: {
Id: '001xx000003DGbYAAW',
Name: 'Acme',
Industry: 'Energy',
AnnualRevenue: 1200000,
Owner: { Name: 'Sam Rivera' }
}
}The second payload has three problems:
- Stale data. The copy can differ from the record by the time a subscriber uses it. A subscriber that edits and saves the record might overwrite newer changes.
- Field coupling. Every subscriber depends on the publisher having queried exactly those fields. If the publisher drops
Industryfrom its query, subscribers break. - Wasted size. The message is copied for each subscriber that receives it.
With an identifier, each subscriber fetches only the fields it needs, using getRecord, a wire adapter, or Apex. The data then comes from the same source as the rest of the page, and Lightning Data Service caches it.
A small amount of extra context is fine. A label shown in the subscriber's header, or a flag such as isNew, is cheaper than a second lookup. The test is whether the value belongs to the event ("this record was selected") or to the record itself.
Name fields for the event
Choose field names that describe the event, not the publisher's implementation.
- Use
recordId, notselectedRowKeyoridFromDatatable. - Use
objectApiNamenext torecordIdwhen subscribers might receive records of different objects. - Use
sourceororiginif a component must ignore its own messages.
Name the channel for the event as well. RecordSelected says what happened. AccountListToDetail ties the channel to two specific components and forces a new channel when a third one arrives.
Keep the metadata in step with the payload
The lightningMessageFields entries in the channel file do not validate anything, but they are the only place the contract is written down. List every field the payload can contain.
<?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 selected record's object, such as Account</description>
<fieldName>objectApiName</fieldName>
</lightningMessageFields>
<lightningMessageFields>
<description>Name of the component that published the message</description>
<fieldName>source</fieldName>
</lightningMessageFields>
<masterLabel>Record Selected</masterLabel>
</LightningMessageChannel>Write the description so it states the type, the allowed values, and whether the field can be empty. A developer who has never seen the publisher should be able to write a subscriber from this file alone.
Build the payload in one place
When several components publish to the same channel, each one builds its own object by hand, and the shapes drift apart. A small helper module keeps them consistent.
// force-app/main/default/lwc/recordSelectedPayload/recordSelectedPayload.js
export function createRecordSelectedPayload(recordId, objectApiName, source) {
return {
recordId: recordId ?? null,
objectApiName: objectApiName ?? null,
source: source ?? null
};
}A publisher uses it like this:
import { LightningElement, wire } from 'lwc';
import { publish, MessageContext } from 'lightning/messageService';
import RECORD_SELECTED from '@salesforce/messageChannel/RecordSelected__c';
import { createRecordSelectedPayload } from 'c/recordSelectedPayload';
export default class AccountList extends LightningElement {
@wire(MessageContext)
messageContext;
handleSelect(event) {
const payload = createRecordSelectedPayload(
event.currentTarget.dataset.id,
'Account',
'accountList'
);
publish(this.messageContext, RECORD_SELECTED, payload);
}
}Every message now has the same three keys, and a missing value is always null. Subscribers do not need to tell "key absent" from "key empty".
Validate in the subscriber
Because the platform does not check the payload, the subscriber has to be defensive. The handler runs for every message on the channel, including ones from components written later.
handleMessage(message) {
if (!message || !message.recordId) {
this.selectedId = undefined;
return;
}
if (message.source === 'recordDetail') {
return; // ignore messages this component's own family sent
}
this.selectedId = message.recordId;
}Treat each field as possibly missing and handle that case in a way that matches your user interface. For a detail panel, a missing recordId usually means "show the empty state."
Evolve a payload without breaking subscribers
Channels are shared, so a change to one affects every subscriber, including Aura components and Visualforce pages you may not own. Compatible changes are safe, and incompatible ones need a new channel.
| Change | Compatible? | What to do |
|---|---|---|
| Add an optional field | Yes | Update the metadata description. Subscribers that ignore it keep working |
| Stop sending an optional field | Sometimes | Safe only if no subscriber relies on it |
| Rename a field | No | Send both names for a while, then remove the old one |
| Change a field's type | No | Add a new field instead |
| Change what a field means | No | Create a new channel |
Adding fields is the normal way to grow a payload. When a change cannot be made compatibly, deploy a new channel, for example RecordSelectedV2. Publish to both channels during the migration, move subscribers over one at a time, and then retire the old channel.
Size and frequency
A message is delivered to every active subscriber in scope each time publish runs. Two habits keep this cheap.
- Keep payloads to a few fields. If you find yourself sending a list of records, send a list of identifiers, or store the list in a shared module or Apex-backed cache and send a key.
- Do not publish on every high-frequency event such as
mousemoveor each keystroke. Publish on meaningful changes, or debounce the call.
handleSearchInput(event) {
window.clearTimeout(this.debounceTimer);
const term = event.target.value;
this.debounceTimer = window.setTimeout(() => {
publish(this.messageContext, SEARCH_CHANGED, { term });
}, 300);
}Do not send sensitive data
Any component subscribed to the channel in scope can read the payload, and that includes components that a page builder adds later. Do not send values that a subscriber should not see, such as tokens, session data, or personal data that only some users may view. An identifier is again the safer choice, because the subscriber's own data access applies field-level and record-level security when it loads the record.
Common mistakes
- Sending a function or component reference. The subscriber cannot use it, and it couples components that should be independent.
- Mutating the received message. Treat the message as read-only. Copy values into the component's own fields.
- Assuming a field exists. Check for it, as shown above.
- Using one channel for unrelated events. Subscribers then filter by a
typefield, and the contract becomes unclear. Prefer one channel per event. - Skipping the metadata description. The next developer has to read every publisher to learn the shape.
Exercise
A list component currently publishes { record: { Id, Name, Industry, AnnualRevenue } } on a channel with three subscribers. One subscriber saved changes using the copied AnnualRevenue and overwrote a newer value. Redesign the payload, and say how you would roll the change out so that the other two subscribers keep working.
Show answer
Send identifiers and event context instead of the record, for example { recordId, objectApiName, source }. Each subscriber then loads the fields it needs through Lightning Data Service, so it always reads current data. Because the old field record is removed, this is an incompatible change. Deploy a new channel such as RecordSelectedV2 with the new fields in lightningMessageFields. Publish to both channels during the migration, move each subscriber to the new channel one at a time, and retire the old channel once it has no subscribers. Alternatively, publish the new fields alongside record on the existing channel until every subscriber is migrated, and then stop sending record.
Exercise
Which of these values can safely be a payload field, and what would you send instead for the others? (a) a Date object, (b) a callback function, (c) an array of five record Ids, (d) a reference to the publisher component.
Show answer
(c) is safe, because an array of primitives is serializable. For (a), send an ISO 8601 string such as 2026-11-30T13:11:03Z. For (b), do not send a function. Have the subscriber publish its own message on another channel, or call a shared module. For (d), do not send a component reference. Send the data the subscriber needs, such as an Id, and let each component keep its own internals private.