Sub topic 8
Subscribing from Lightning components and external clients
This chapter assumes you can read a change event, know the /data/AccountChangeEvent channel naming, and are comfortable with Lightning web component (LWC) basics. Apex triggers run inside Salesforce. Two other kinds of consumer sit outside the trigger runtime: Lightning components in the browser, and external systems such as middleware, data pipelines, and microservices. This chapter covers both.
Choosing a subscription method
Salesforce offers three ways to receive change events outside Apex.
| Method | Runs where | Protocol | Payload format | Typical use |
|---|---|---|---|---|
| `lightning/empApi` | Browser, inside a Lightning page | CometD, wrapped by the module | JSON | Refreshing a UI when data changes |
| CometD (Streaming API) | External client | Bayeux over HTTP long polling | JSON | Existing integrations already built on CometD |
| Pub/Sub API | External client | gRPC over HTTP/2 | Avro binary | New external integrations, high volume |
For new external work, prefer Pub/Sub API. It is the newer interface, and it gives the client control over how fast events arrive. CometD remains supported, so you will meet it in existing code.
All three methods subscribe to the same channel, for example /data/AccountChangeEvent. They also share the same replay ID and retention rules, which the next chapter covers in detail. This chapter only shows where each method accepts a replay value.
Subscribing from a Lightning web component
The lightning/empApi module hides the CometD handshake. It handles authentication through the user's session. You call four functions.
subscribe(channel, replayId, callback)opens a subscription and returns a Promise that resolves to a subscription object.unsubscribe(subscription, callback)closes it.onError(callback)registers a handler for connection and protocol errors.setDebugFlag(flag)andisEmpEnabled()help with diagnostics.
The replay ID is the second argument to subscribe. The value -1 means "only events published after I subscribe". The value -2 means "everything still in the retention window, then new events".
Here is a component that logs every Account change:
import { LightningElement } from 'lwc';
import { subscribe, unsubscribe, onError } from 'lightning/empApi';
export default class AccountChangeListener extends LightningElement {
subscription = null;
channelName = '/data/AccountChangeEvent';
connectedCallback() {
onError((error) => {
console.error('empApi error', JSON.stringify(error));
});
subscribe(this.channelName, -1, (message) => {
const header = message.data.payload.ChangeEventHeader;
console.log(header.changeType, header.recordIds);
}).then((response) => {
this.subscription = response;
});
}
disconnectedCallback() {
if (this.subscription) {
unsubscribe(this.subscription, () => {});
}
}
}The callback receives a message with two parts. message.data.payload holds the change event: the ChangeEventHeader plus the changed fields. message.data.event.replayId holds the position of this event in the stream.
Handling the message correctly
A subscriber to a CDC channel receives events for every change to that object, including changes the current user did not make. In a busy org, a component that refreshes on every event will refresh constantly. Filter early.
import { LightningElement, api } from 'lwc';
import { subscribe, unsubscribe, onError } from 'lightning/empApi';
export default class AccountPhoneWatcher extends LightningElement {
@api recordId;
subscription = null;
lastReplayId = -1;
channelName = '/data/AccountChangeEvent';
connectedCallback() {
onError((error) => console.error('empApi error', JSON.stringify(error)));
subscribe(this.channelName, -1, (message) => this.handleMessage(message))
.then((response) => {
this.subscription = response;
});
}
handleMessage(message) {
this.lastReplayId = message.data.event.replayId;
const header = message.data.payload.ChangeEventHeader;
const touchesThisRecord = header.recordIds.includes(this.recordId);
const phoneChanged = header.changedFields.includes('Phone');
if (touchesThisRecord && phoneChanged) {
console.log('Phone is now', message.data.payload.Phone);
}
}
disconnectedCallback() {
if (this.subscription) {
unsubscribe(this.subscription, () => {});
}
}
}Two details matter here.
recordIdsis an array. One event can describe several records that changed in the same way in one transaction, so useincludes, not equality.- On an
UPDATE, the payload carries only the changed fields. IfPhonedid not change,payload.Phoneis absent. CheckchangedFieldsbefore you read a value.
An LWC subscription lives only as long as the component. A browser tab that closes loses its position, and the component starts over with -1 the next time it loads. For UI refresh that is usually fine, because the component re-queries current data when it loads. If you need every event, a browser is the wrong consumer. Use a server-side subscriber.
Common component errors
- Forgetting
disconnectedCallback. The subscription stays open after the component is gone, and the callback keeps running against a removed component. - Subscribing to a channel for an object that has no CDC enabled. The subscription call may succeed while no events ever arrive, so check the entity selection in Setup first.
- Assuming
onErrorfires for a missing channel. Test with a deliberate change and watch the browser console. - Treating the callback as a transaction. Events arrive after the commit, so a refresh that reads the record sees the committed data. But two events for the same record can arrive in quick succession, so make handlers idempotent.
Subscribing from an external client
An external client has to do three things that empApi does for you: authenticate, open a long-lived connection, and track its own replay position.
Correction: the diagram must use the "diagram mermaid" fence format. Here it is in full.
Pub/Sub API
The client connects to api.pubsub.salesforce.com:7443 over gRPC. Each call carries three pieces of metadata: the access token, the instance URL, and the tenant (org) ID. The flow is:
- Get an access token through an OAuth flow suited to server use, such as the JWT bearer flow or client credentials.
- Call
GetTopicfor the channel name to get the schema ID. - Call
GetSchemato fetch the Avro schema. Cache it by ID. Each event carries only the schema ID, so you decode against the cached schema. - Open the bidirectional
Subscribestream and send aFetchRequest. - Decode each event's Avro payload, process it, and store its replay ID.
The FetchRequest has a replay_preset field with three values: LATEST for new events only, EARLIEST for the start of the retention window, and CUSTOM to resume from a replay ID you stored. The num_requested field is the flow-control setting. The server sends at most that many events, and then waits until you request more. A slow consumer therefore cannot be flooded, which CometD cannot guarantee.
Avro changes how you read the header. In Pub/Sub API, changedFields, nulledFields, and diffFields in the header are bitmaps, not lists of names. A bitmap is a compact encoding where each bit position stands for a field in the schema. Salesforce provides client libraries and examples that decode bitmaps for you, so use one instead of writing the bit logic yourself.
CometD
A CometD client connects to https://<instance>/cometd/<apiVersion>, performs the Bayeux handshake with the access token in an Authorization header, and subscribes to /data/AccountChangeEvent. The replay value goes in a replay extension that you register with the client. CometD pushes events as they arrive, with no flow control, and it sends JSON. The payload has the same shape as in the LWC example. The protocol also needs periodic reconnects, which CometD libraries handle.
Storing the replay position
An external subscriber must write the replay ID of each processed event to durable storage, such as a database table or a key-value store. On restart, subscribe with CUSTOM and that ID. Without it, a restart either misses events (LATEST) or reprocesses everything still retained (EARLIEST).
Store the ID only after the work for that event has succeeded. If you store it first and then crash, the event is lost. If you store it after, a crash causes a repeat, which an idempotent handler absorbs.
Authentication and access
A subscriber sees only what its user can see. The user needs read access to the object, and field-level security hides fields the user cannot read. The next chapters cover this in detail. For now, remember that an external integration user needs the same care as any other API user. Give it a dedicated integration user, and avoid reusing an administrator.
Exercise
An external service subscribes through Pub/Sub API with LATEST and stores no replay IDs. It is down for ten minutes during a deployment. What happens to the changes made in those ten minutes, and what should the service do differently?
Show answer
Those changes are missed, because LATEST starts after the moment of reconnecting. The service should write the replay ID of each processed event to durable storage, only after processing succeeds. On restart it should subscribe with the CUSTOM preset and the stored ID. This works as long as the downtime stays inside the retention window.
Exercise
In an LWC, an update event arrives and message.data.payload.Phone is undefined, although the code expects a phone number. Give the likely cause and a fix.
Show answer
On an update, the payload holds only the fields that changed, and Phone did not change in this event. Check header.changedFields.includes('Phone') before reading payload.Phone.