Sub topic 9
Subscribing in a Lightning Web Component with empApi
This chapter shows how a Lightning Web Component (LWC) listens to a platform event in the browser. It uses the lightning/empApi module, which wraps the streaming connection to the event bus. You will build a listener, learn what the replay ID argument does, and see the errors that most often break a subscription.
Prerequisites
This chapter assumes you already know the following:
- Basic LWC structure: a JavaScript class, an HTML template, and lifecycle hooks such as
connectedCallbackanddisconnectedCallback. - The
Order_Shipped__eplatform event from the earlier chapters, with the custom fieldsOrder_Number__candStatus__c. - That a subscriber receives events after they are published to the event bus. The bus keeps events for a limited time, which the replay chapter covers in full.
What empApi does
lightning/empApi is a module that ships with Lightning Experience. It opens one CometD streaming connection for the page and lets components subscribe to channels on it. CometD is the long-polling and WebSocket messaging protocol that Salesforce streaming is built on. You do not manage the connection yourself. You call functions from the module, and it handles the handshake and the session.
The module exports these functions:
| Function | Purpose |
|---|---|
| `subscribe(channel, replayId, callback)` | Starts a subscription and returns a promise that resolves to a subscription object. |
| `unsubscribe(subscription, callback)` | Ends a subscription. |
| `onError(callback)` | Registers a handler for errors on the streaming connection. |
| `setDebugFlag(flag)` | Turns on debug logging of the module. |
| `isEmpEnabled()` | Returns a promise that resolves to whether the module is available in the current context. |
The channel name for a platform event always has the form /event/<API name>. For Order_Shipped__e the channel is /event/Order_Shipped__e. The __e suffix is part of the name.
The flow of a message
A publisher puts an event on the bus. The browser, through empApi, holds an open subscription. When an event arrives on the channel, empApi calls your callback with a message object.
A complete listener
The component below subscribes when it is added to the page and unsubscribes when it is removed.
import { LightningElement } from 'lwc';
import { subscribe, unsubscribe, onError } from 'lightning/empApi';
export default class OrderShippedListener extends LightningElement {
channelName = '/event/Order_Shipped__e';
subscription = null;
connectedCallback() {
onError((error) => {
console.error('empApi error', JSON.stringify(error));
});
subscribe(this.channelName, -1, (message) => {
const payload = message.data.payload;
console.log('Order shipped: ' + payload.Order_Number__c);
}).then((response) => {
this.subscription = response;
});
}
disconnectedCallback() {
if (this.subscription) {
unsubscribe(this.subscription, () => {});
}
}
}Read it in four parts.
onErrorregisters a handler for connection-level problems, such as a failed handshake or a dropped session. It does not fire for errors inside your own callback.subscribetakes the channel, the replay ID, and a callback. The callback runs once for every event delivered..thenreceives the subscription object. You keep it so you can unsubscribe later.disconnectedCallbackcleans up. Without it, the subscription stays open after the component leaves the page.
Reading the message
Each message passed to your callback has this shape:
{
channel: '/event/Order_Shipped__e',
data: {
schema: 'abc123...',
payload: {
Order_Number__c: '00012345',
Status__c: 'Shipped',
CreatedDate: '2026-12-01T09:02:32.000Z',
CreatedById: '005...'
},
event: {
replayId: 4521
}
}
}Two fields matter most:
message.data.payloadholds the custom fields you defined, plusCreatedDateandCreatedById. The keys use the field API names, so the__csuffix is present.message.data.event.replayIdis the position of this event on the bus. Store it if you want to resume from that point later.
Choosing a replay ID
The second argument to subscribe decides which events you receive.
| Value | Meaning |
|---|---|
| `-1` | Only events published after the subscription starts. |
| `-2` | All events still in the retention window, then new events. |
| A specific replay ID | All retained events published after that ID, then new events. |
Use -1 for a live display such as a toast notification or a status banner. A user who opens the page does not care about events from an hour ago.
Use -2 with care. It replays every retained event each time the component loads, so the callback may run many times at once. Your code must tolerate that burst and must not assume that every event is new.
Use a stored replay ID when you need to continue without gaps. The component saves message.data.event.replayId somewhere durable, such as sessionStorage, and passes it back on the next load. Remember that an ID older than the retention window cannot be honored. Salesforce then delivers whatever is still retained, so you can miss events without an error.
Reacting to events in the UI
Logging to the console proves the subscription works. A real component updates reactive state. The next example keeps the last five events and renders them.
import { LightningElement } from 'lwc';
import { subscribe, unsubscribe, onError } from 'lightning/empApi';
const MAX_ITEMS = 5;
export default class OrderShippedFeed extends LightningElement {
channelName = '/event/Order_Shipped__e';
subscription = null;
orders = [];
connectedCallback() {
onError((error) => {
console.error('empApi error', JSON.stringify(error));
});
subscribe(this.channelName, -1, (message) => {
const payload = message.data.payload;
const entry = {
key: String(message.data.event.replayId),
orderNumber: payload.Order_Number__c,
status: payload.Status__c
};
this.orders = [entry, ...this.orders].slice(0, MAX_ITEMS);
}).then((response) => {
this.subscription = response;
});
}
disconnectedCallback() {
if (this.subscription) {
unsubscribe(this.subscription, () => {});
}
}
}The matching template:
<template>
<lightning-card title="Recent shipments">
<ul class="slds-p-around_medium">
<template for:each={orders} for:item="order">
<li key={order.key}>
{order.orderNumber}: {order.status}
</li>
</template>
</ul>
</lightning-card>
</template>The code assigns a new array to this.orders instead of calling push. LWC tracks reassignment of a class field, so the template re-renders. The replay ID serves as the list key because it is unique per event.
Making the component reusable
Hard-coding the channel limits the component to one event. You can expose it as a property and let an administrator set it in Lightning App Builder.
import { LightningElement, api } from 'lwc';
import { subscribe, unsubscribe, onError } from 'lightning/empApi';
export default class EventListener extends LightningElement {
@api channelName = '/event/Order_Shipped__e';
subscription = null;
connectedCallback() {
onError((error) => {
console.error('empApi error', JSON.stringify(error));
});
subscribe(this.channelName, -1, (message) => {
this.dispatchEvent(
new CustomEvent('eventreceived', { detail: message.data.payload })
);
}).then((response) => {
this.subscription = response;
});
}
disconnectedCallback() {
if (this.subscription) {
unsubscribe(this.subscription, () => {});
}
}
}The component forwards each payload as a DOM CustomEvent, so a parent can react without knowing how the data arrived.
Where empApi works
- It works in Lightning Experience and in Lightning communities that use the Lightning runtime. It is not meant for Visualforce pages, and it does not apply to Lightning Web Runtime sites.
- It is a client-side feature. A user must be signed in, and the user needs read access to the event. Grant that access with the Read permission on the platform event in a profile or permission set.
- It does not work in Lightning Out or in a standalone app outside Salesforce. For those cases, an external subscriber uses the Pub/Sub API, covered in a later chapter.
The module may also be unavailable in some contexts, such as a preview. Call isEmpEnabled() first if your component can load in such places.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Nothing arrives, no error | Wrong channel name, such as `/event/Order_Shipped` without `__e` | Use the exact API name with the `__e` suffix. |
| `403::Unknown client` or a handshake error | The user lacks read access to the event | Add Read access on the event to the user's profile or a permission set. |
| Callback runs many times on load | Replay ID `-2` or an old stored ID | Use `-1`, or make the handler idempotent. |
| Duplicate messages after navigating | A subscription was never closed | Unsubscribe in `disconnectedCallback`. |
| Events missed after a long idle period | The session or connection dropped, and the stored replay ID is outside retention | Handle `onError`, re-subscribe, and store the last replay ID. |
| `payload.Order_Number` is undefined | The `__c` suffix was left off | Use the field API name, `Order_Number__c`. |
Design guidance
An LWC subscription suits notifications and live views. It reflects state to a user who is looking at the page right now. It is a poor place for business logic, because the component runs only while a browser tab has it open. If no one is on the page, no code runs.
When the event must cause a record change, put that work in an Apex trigger or a platform event-triggered flow, and let the component only display the result.
Exercise
A component subscribes to /event/Order_Shipped__e with replay ID -2. Users report that when they open the page, the callback fires dozens of times and a toast appears for each old order. What is the cause, and what change fixes it?
Show answer
Replay ID -2 asks for every event still in the retention window, so the callback receives all retained events on load, then new ones. For a live notification, subscribe with -1 so only events published after the subscription starts are delivered. If old events must be processed, make the handler skip events it has already handled, for example by comparing message.data.event.replayId with a stored value.
Exercise
A component calls subscribe in connectedCallback but never calls unsubscribe. A user moves between tabs in the app and returns several times. What symptom would you expect, and where should the fix go?
Show answer
Each visit can create another subscription that is never closed, so one event triggers the callback more than once and the old components keep running. Save the object returned by subscribe, and call unsubscribe with it inside disconnectedCallback.