lwc-server-sent-events
Use when building LWCs that must react to live server pushes — Platform Events, Change Data Capture, or streaming updates — via the lightning/empApi (CometD) subscription model. Covers lifecycle, replayId, error handling, reconnection, scale considerations, and multi-tab behavior. Does NOT cover publishing events (see platform-events or apex-platform-events).
Best use case
lwc-server-sent-events is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Use when building LWCs that must react to live server pushes — Platform Events, Change Data Capture, or streaming updates — via the lightning/empApi (CometD) subscription model. Covers lifecycle, replayId, error handling, reconnection, scale considerations, and multi-tab behavior. Does NOT cover publishing events (see platform-events or apex-platform-events).
Teams using lwc-server-sent-events should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/lwc-server-sent-events/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How lwc-server-sent-events Compares
| Feature / Agent | lwc-server-sent-events | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Use when building LWCs that must react to live server pushes — Platform Events, Change Data Capture, or streaming updates — via the lightning/empApi (CometD) subscription model. Covers lifecycle, replayId, error handling, reconnection, scale considerations, and multi-tab behavior. Does NOT cover publishing events (see platform-events or apex-platform-events).
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# LWC Server-Sent / Streaming Events
## Purpose
Salesforce's streaming model — CometD under `lightning/empApi` — is the
closest thing LWCs get to Server-Sent Events. Teams reach for it when a
record page should "auto-refresh" on server changes, when a custom
dashboard needs near-real-time data, or when a long-running job needs to
stream progress to the user. The shape is simple but the failure modes
(disconnection, missed events, replay storms, memory leaks) are not. This
skill codifies subscription lifecycle, replayId strategy, error handling,
and coordination across components and tabs.
## Recommended Workflow
1. **Confirm streaming is the right tool.** For record changes, consider
`getRecordNotifyChange` or Lightning Data Service caches first.
2. **Pick the channel.** Platform Event (`/event/<EventName>__e`), CDC
(`/data/<ObjectName>ChangeEvent`), or Generic Streaming (`/u/...`).
3. **Subscribe in `connectedCallback`.** Always unsubscribe in
`disconnectedCallback`. Store the subscription reference.
4. **Decide replayId.** `-1` = new events only, `-2` = retained events
(24h), or a specific replayId if you track last-seen.
5. **Handle errors.** `onError` must log and, where appropriate, re-subscribe
with backoff.
6. **De-duplicate across tabs.** A user with 3 tabs open will receive each
event 3x. Decide whether that matters.
7. **Respect governor limits.** Daily event delivery allocation is finite.
## Lifecycle Template
```js
import { subscribe, unsubscribe, onError, setDebugFlag } from 'lightning/empApi';
connectedCallback() {
this.registerErrorListener();
this.handleSubscribe();
}
disconnectedCallback() {
this.handleUnsubscribe();
}
handleSubscribe() {
const channel = '/event/Order_Status__e';
const replayId = -1; // new only
subscribe(channel, replayId, this.onEvent.bind(this))
.then((sub) => (this._subscription = sub))
.catch((err) => this.handleError(err));
}
handleUnsubscribe() {
if (this._subscription) {
unsubscribe(this._subscription, () => {});
this._subscription = null;
}
}
onEvent(message) {
// message.data.payload
}
registerErrorListener() {
onError((err) => this.handleError(err));
}
```
## Replay Strategy
| Value | Behavior | Use When |
|---|---|---|
| `-1` | Only new events after subscribe | Best-effort UI updates |
| `-2` | All retained events (24h window) | Component needs history on open |
| specific replayId | Resume from a known point | Reliability-critical workflows |
Tracking replayId client-side requires persistence (localStorage keyed by
user) and careful cross-tab coordination.
## Error And Reconnect
- Network drop: empApi emits an error; re-subscribe with exponential
backoff (1s, 2s, 5s, 30s cap).
- 403 on channel: permissions issue; log and give up.
- Event pool exhausted (server-side): surface the error; ops concern.
## Multi-Tab / Multi-Component
- Each LWC instance = one subscription = one delivery.
- To de-duplicate, elect a leader tab (BroadcastChannel) and forward
events to other tabs, or accept duplicates if the handler is idempotent.
- For multi-component on one page, consider subscribing once at a parent
and `dispatchEvent`-ing to children.
## Scale
- Platform Event daily limit varies by edition; confirm for your org.
- One component per user subscribed to a high-volume channel = linear
multiplier on delivery counts.
- For very high volume, CDC may be cheaper than Platform Events for the
same data shape.
## Anti-Patterns (see references/llm-anti-patterns.md)
- Subscribing in every child component.
- Forgetting `disconnectedCallback` unsubscribe (memory leak).
- Trusting `-1` for reliability-critical flows.
- Handling events without idempotency.
## Official Sources Used
- Lightning empApi — https://developer.salesforce.com/docs/platform/lwc/guide/use-comm-empapi.html
- Platform Events Developer Guide — https://developer.salesforce.com/docs/atlas.en-us.platform_events.meta/platform_events/platform_events_intro.htm
- Change Data Capture — https://developer.salesforce.com/docs/atlas.en-us.change_data_capture.meta/change_data_capture/cdc_intro.htm
- Streaming API — https://developer.salesforce.com/docs/atlas.en-us.api_streaming.meta/api_streaming/intro_stream.htmRelated Skills
platform-events-integration
Use when publishing Platform Events from external systems via REST API, subscribing to Platform Events from outside Salesforce via CometD or Pub/Sub API, designing replay ID strategy for durable external consumers, or handling high-volume event delivery guarantees. Trigger keywords: 'external publish platform event', 'CometD subscribe', 'Pub/Sub API', 'replay ID external', 'durable subscription', 'RetainUntilDate'. NOT for Apex-only event publishing or triggering (use platform-events-apex). NOT for Change Data Capture external subscription (use change-data-capture-integration).
pause-elements-and-wait-events
Use this skill when designing or troubleshooting flows that need to suspend execution and wait for an external signal — either a time-based alarm or a platform event. Trigger keywords: pause element, wait element, flow interview suspension, alarm event, platform event resume, async interview. NOT for scheduled flows that recur on a fixed schedule (use scheduled-flows), and NOT for record-triggered flow scheduled paths on a single record (those are set in the Start element, not a Pause element).
flow-platform-events-integration
Use when Flow is a Platform Event publisher, subscriber, or both. Triggers: 'publish platform event from flow', 'platform-event-triggered flow', 'high-volume platform event', 'publish after commit vs immediate', 'PE subscriber error handling', 'integration fan-out from save'. NOT for Change Data Capture (see integration skills) or for generic async work that does not need pub/sub (see flow/scheduled-flows).
flow-and-platform-events
Publish and subscribe to Platform Events from Flow for async decoupling, high-volume triggers, and cross-org signaling. NOT for regular DML-triggered flows.
copado-essentials
Use when configuring or operating Copado Essentials deployment pipelines — including user story creation, branch management, promotion paths, conflict resolution, and choosing between Work Items and Pull Request deployment modes. Trigger keywords: copado essentials pipeline, user story deployment copado, copado branch management, copado conflict resolution, copado promotion path. NOT for native Salesforce CLI or SFDX workflows without Copado, NOT for Copado Enterprise (full ALM) features beyond Essentials tier, NOT for DevOps tool selection (use devops/salesforce-devops-tooling-selection).
data-cloud-consent-and-privacy
Use this skill when implementing consent management, data subject request processing, or data retention policies in Data Cloud — including the ssot__ContactPointConsent__dlm DMO, consent-aware segmentation filters, GDPR/CCPA data deletion requests via Privacy Center or Data Deletion API, and per-DLO retention policy configuration. Triggers on: consent-aware segmentation in Data Cloud, Data Cloud GDPR deletion request, right to be forgotten Data Cloud, ContactPointConsent DMO, Data Cloud data retention policy. NOT for CRM-layer consent management (ContactPointTypeConsent standard objects on Salesforce org — use gdpr-data-privacy skill), not for general GDPR implementation outside Data Cloud.
consent-data-model-health
Use this skill when designing, implementing, querying, or troubleshooting the Health Cloud consent data model — specifically the five-object HIPAA authorization hierarchy (DataUsePurpose → AuthorizationForm → AuthorizationFormText → AuthorizationFormDataUse → AuthorizationFormConsent). Trigger keywords: authorization form consent, ConsentGiverId, AuthorizationFormConsent SOQL, CareProgramEnrollee consent gate, PHI consent trail, consent hierarchy setup. NOT for marketing consent or standard email opt-out tracking. NOT for ContactPointConsent or ContactPointTypeConsent objects used in Marketing Cloud or standard Salesforce Privacy Center.
marketing-consent-architecture
Consent management architecture across Marketing Cloud and CRM: data model design, cross-system sync patterns, and compliance design for GDPR/CCPA. Trigger keywords: consent data model, ContactPointConsent, ContactPointTypeConsent, Individual object, CRM system of record, MC consent sync, opt-in opt-out architecture, data use purpose, lawful basis. NOT for individual consent setup steps or configuring a single publication list.
ssjs-server-side-javascript
Use this skill when writing, debugging, or reviewing Server-Side JavaScript (SSJS) in Salesforce Marketing Cloud — Script Activities, Cloud Pages, and Landing Pages. Covers WSProxy for SOAP API access, Script.Util.HttpRequest for outbound REST calls, error handling patterns, execution limits, and SSJS/AMPscript interoperability. NOT for AMPscript-only personalization logic inside Email Studio sends, not for standard Apex (Salesforce Platform), and not for client-side JavaScript in Experience Cloud or LWC.
sf-cli-and-sfdx-essentials
Use this skill when a developer needs to authenticate orgs with sf CLI, set up a Salesforce DX project, create scratch orgs, push or pull source between the local repo and a scratch org, deploy or retrieve metadata to sandboxes or production using package.xml manifests, or diagnose common sf CLI errors. Trigger keywords: sf CLI, sfdx, scratch org, source push, source pull, deploy, retrieve, package.xml, org login, sf project. NOT for full CI/CD pipeline design (use devops skills) or Metadata API SOAP programming (that is SOAP API work, not CLI).
platform-events-apex
Use when publishing or subscribing to Salesforce Platform Events from Apex, comparing Platform Events with Change Data Capture, or designing event-triggered error handling and monitoring. Triggers: 'EventBus.publish', 'platform event trigger', 'CDC vs Platform Events', 'replay ID', 'high-volume event'. NOT for Flow-only publish/subscribe automation.
salesforce-mcp-server-setup
Use this skill to install and configure the salesforce-mcp-lib Apex package and npm stdio proxy so that an MCP client (Claude Desktop, Cursor, ChatGPT) can call Salesforce org data and logic via the Model Context Protocol. Trigger keywords: MCP server, salesforce-mcp-lib, Claude Desktop Salesforce, MCP proxy setup, Apex JSON-RPC, MCP Connected App. NOT for Salesforce Hosted MCP Servers (Agentforce-native hosted endpoints), NOT for Flow-based tool definitions, NOT for OmniStudio integrations.