lwc-pubsub-patterns

Sibling-component communication in LWC — Lightning Message Service (the modern, supported pattern via Message Channels), the legacy `pubsub` utility (community-shared, predates LMS), `scope = APPLICATION` vs `scope = ACTIVE` semantics, when LMS is the wrong tool (parent-child should use props / `CustomEvent`; cross-tab needs Platform Events), and the migration from `pubsub` to LMS. Covers the message channel `.messageChannel-meta.xml` definition, the `@wire(MessageContext)` pattern, `subscribe` / `unsubscribe` lifecycle, and avoiding leaked subscriptions on disconnectedCallback. NOT for parent-child LWC props / events (see lwc/lwc-component-communication), NOT for cross-org / cross-user messaging (use Platform Events).

Best use case

lwc-pubsub-patterns is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Sibling-component communication in LWC — Lightning Message Service (the modern, supported pattern via Message Channels), the legacy `pubsub` utility (community-shared, predates LMS), `scope = APPLICATION` vs `scope = ACTIVE` semantics, when LMS is the wrong tool (parent-child should use props / `CustomEvent`; cross-tab needs Platform Events), and the migration from `pubsub` to LMS. Covers the message channel `.messageChannel-meta.xml` definition, the `@wire(MessageContext)` pattern, `subscribe` / `unsubscribe` lifecycle, and avoiding leaked subscriptions on disconnectedCallback. NOT for parent-child LWC props / events (see lwc/lwc-component-communication), NOT for cross-org / cross-user messaging (use Platform Events).

Teams using lwc-pubsub-patterns 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

$curl -o ~/.claude/skills/lwc-pubsub-patterns/SKILL.md --create-dirs "https://raw.githubusercontent.com/PranavNagrecha/AwesomeSalesforceSkills/main/skills/lwc/lwc-pubsub-patterns/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/lwc-pubsub-patterns/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How lwc-pubsub-patterns Compares

Feature / Agentlwc-pubsub-patternsStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Sibling-component communication in LWC — Lightning Message Service (the modern, supported pattern via Message Channels), the legacy `pubsub` utility (community-shared, predates LMS), `scope = APPLICATION` vs `scope = ACTIVE` semantics, when LMS is the wrong tool (parent-child should use props / `CustomEvent`; cross-tab needs Platform Events), and the migration from `pubsub` to LMS. Covers the message channel `.messageChannel-meta.xml` definition, the `@wire(MessageContext)` pattern, `subscribe` / `unsubscribe` lifecycle, and avoiding leaked subscriptions on disconnectedCallback. NOT for parent-child LWC props / events (see lwc/lwc-component-communication), NOT for cross-org / cross-user messaging (use 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 Pub/Sub Patterns

Lightning Web Components communicate naturally **down** the
component tree (parent passes props to child) and **up** (child
fires `CustomEvent`, parent listens). The harder case is **sibling**
communication: two components on the same page that have no
parent-child relationship.

Salesforce's modern answer is **Lightning Message Service (LMS)**.
Before LMS shipped, the community converged on a custom `pubsub`
utility (a singleton event-bus pattern in JavaScript). Both
patterns appear in real codebases. This skill maps the choice and
covers the implementation discipline that prevents subscription
leaks.

## When LMS is the right tool

LMS is the right tool when:

- The components are siblings (no shared parent that can mediate).
- The communication is within a single Lightning page or app
  (LMS scope is `APPLICATION` or `ACTIVE`, not cross-tab).
- The publishers / subscribers may be a mix of LWC, Aura, and
  Visualforce — LMS supports all three.

**LMS is NOT the right tool for:**

- **Parent-child.** Use props (down) and `CustomEvent` (up).
  LMS in parent-child is overkill and obscures intent.
- **Cross-tab / cross-window.** LMS does not cross browser tabs.
  Use Platform Events for cross-tab or cross-user signaling.
- **High-frequency streaming.** LMS is for discrete events, not
  100Hz updates.

## The Message Channel definition

Message channels are metadata. Define a channel at
`force-app/main/default/messageChannels/MyChannel.messageChannel-meta.xml`:

```xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningMessageChannel xmlns="http://soap.sforce.com/2006/04/metadata">
    <masterLabel>My Channel</masterLabel>
    <isExposed>true</isExposed>
    <description>Sibling sync: search component to results component.</description>
    <lightningMessageFields>
        <fieldName>recordId</fieldName>
        <description>The record selected in the search component.</description>
    </lightningMessageFields>
    <lightningMessageFields>
        <fieldName>action</fieldName>
        <description>One of: 'select', 'clear'.</description>
    </lightningMessageFields>
</LightningMessageChannel>
```

`isExposed = true` means other namespaces can use it. Set to false
for managed-package internal channels.

## Publish / subscribe in LWC

```javascript
import { LightningElement, wire } from 'lwc';
import {
    publish, subscribe, unsubscribe, MessageContext, APPLICATION_SCOPE
} from 'lightning/messageService';
import MY_CHANNEL from '@salesforce/messageChannel/MyChannel__c';

export default class SearchComponent extends LightningElement {
    @wire(MessageContext) messageContext;
    subscription = null;

    connectedCallback() {
        this.subscription = subscribe(
            this.messageContext,
            MY_CHANNEL,
            (msg) => this.handleMessage(msg),
            { scope: APPLICATION_SCOPE }
        );
    }

    disconnectedCallback() {
        unsubscribe(this.subscription);
        this.subscription = null;
    }

    publishSelection(recordId) {
        publish(this.messageContext, MY_CHANNEL, {
            recordId,
            action: 'select'
        });
    }

    handleMessage(msg) { /* ... */ }
}
```

Two things to get right:

1. `@wire(MessageContext)` provides the message context the
   subscribe / publish calls require.
2. **Always** unsubscribe in `disconnectedCallback` to prevent
   memory leaks across page navigations.

## `scope: APPLICATION` vs `scope: ACTIVE`

| Scope | Receives messages from |
|---|---|
| `APPLICATION_SCOPE` | All subscribers anywhere in the Lightning Experience app |
| `ACTIVE` (default) | Only subscribers in the active Lightning navigation context (current tab in console UX, current app) |

`APPLICATION_SCOPE` is broader; use it when the publisher and
subscriber may live in different apps within the same Lightning
session (e.g. utility bar component and main page). `ACTIVE` is
the default and is what you usually want for pages that should
only talk to themselves.

## The legacy `pubsub` utility

Pre-LMS, a community-shared utility module called `pubsub` (often
literally named that in source) provided a singleton event bus.
Pattern:

```javascript
import { fireEvent, registerListener, unregisterListener } from 'c/pubsub';

connectedCallback() {
    registerListener('mySearchEvent', this.handleEvent, this);
}
disconnectedCallback() {
    unregisterAllListeners(this);
}
```

It works but has limits:

- Custom utility you maintain (LMS is platform-supported).
- Cannot be consumed by Aura / Visualforce.
- Singleton state across components — leaks easier.

**Migration.** Replace `c/pubsub` import with
`lightning/messageService`. Replace the event name with a Message
Channel. Most renames are mechanical.

## Recommended Workflow

1. **Confirm sibling communication is required.** Parent-child should use props / `CustomEvent`; only reach for LMS when there is no shared parent.
2. **Confirm cross-tab is not required.** LMS does not cross tabs. For cross-tab, use Platform Events.
3. **Define the Message Channel.** Create `MyChannel.messageChannel-meta.xml` with named fields and a description. Treat the channel as a contract; named fields are the schema.
4. **Implement publish / subscribe.** Use `@wire(MessageContext)`; subscribe in `connectedCallback`; **always** unsubscribe in `disconnectedCallback`.
5. **Pick the scope.** `APPLICATION_SCOPE` for cross-app within the Lightning session; default (`ACTIVE`) for same-page.
6. **Test the unsubscribe.** Navigate away and back; the previous subscription should not fire on the second visit. Memory leaks here surface as duplicate handler invocations.
7. **For legacy `pubsub` users**, migrate to LMS rather than extending the utility. Custom utility maintenance cost compounds.

## What This Skill Does Not Cover

| Topic | See instead |
|---|---|
| Parent-child LWC props / `CustomEvent` | `lwc/lwc-component-communication` |
| Cross-tab or cross-user events | Platform Events / `integration/change-data-capture-patterns` |
| Aura-to-LWC interop generally | `lwc/aura-lwc-interop-patterns` |
| LWC reactivity (`@track`, `@api`, `@wire`) | `lwc/lwc-reactivity-patterns` |

Related Skills

mfa-enforcement-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Design MFA enforcement: auto-enablement, Salesforce Authenticator rollout, exceptions, service accounts, API-only users, SSO interop, and audit. Trigger keywords: MFA, multi-factor, two-factor, Salesforce Authenticator, MFA exception, MFA SSO, api-only MFA. Does NOT cover: end-user password policies, device-trust posture, or non-Salesforce IdP configuration.

encrypted-field-query-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Design SOQL, filters, reporting, and indexes against Shield Platform Encryption fields. Trigger keywords: Shield Platform Encryption, encrypted field query, probabilistic vs deterministic encryption, encrypted SOQL filter, encrypted field index. Does NOT cover: Classic Encryption (deprecated), field-level security policy, or tenant secret key rotation.

apex-managed-sharing-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Grant row-level access programmatically via __Share records when declarative sharing rules cannot express the policy. NOT for OWD, role hierarchy, or criteria-based sharing rule design.

omnistudio-testing-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when testing or validating OmniStudio components — OmniScript preview, Integration Procedure step debugging, DataRaptor field-mapping validation, and end-to-end UTAM-based automation. NOT for Apex unit testing or standard Flow debugging.

omnistudio-error-handling-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when designing fault behavior across Integration Procedures, DataRaptors, OmniScripts, and FlexCards — error routing, user-facing messaging, retry semantics, and idempotency. Triggers: 'omnistudio error', 'integration procedure fault', 'dataraptor error handling', 'omniscript retry', 'flexcard action failure'. NOT for general Apex exception design or Flow fault paths.

omnistudio-ci-cd-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when designing or implementing CI/CD pipelines for OmniStudio components — DataPack export/import, versioning, environment promotion, and automated deployment. NOT for standard Salesforce metadata CI/CD or Apex-only pipelines.

omniscript-design-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when designing or reviewing OmniScripts for guided experiences, step structure, branching, save/resume, and the boundary between OmniScript, Integration Procedures, DataRaptors, and custom LWCs. Triggers: 'omniscript design', 'too many steps in omniscript', 'save and resume omniscript', 'branching in omniscript', 'when should this be an integration procedure'. NOT for deep Integration Procedure or DataRaptor design when the guided interaction layer is not the main concern.

integration-procedure-cacheable-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when designing Integration Procedures (IPs) with platform cache to cut latency and callout load. Covers cache key design, TTL selection, per-user vs org-wide partitions, invalidation on data changes, and safe fallback on cache miss/stale. Does NOT cover general IP authoring (see omnistudio-error-handling-patterns) or LWC client-side caching.

flexcard-design-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when designing, building, or reviewing OmniStudio FlexCards — including data source selection, card states, actions, conditional visibility, flyout configuration, and child card iteration. Triggers: 'FlexCard', 'card template', 'flyout', 'card action', 'card state', 'data source', 'child card', 'conditional visibility'. NOT for OmniScript design, standalone LWC development, or Apex controller architecture outside the FlexCard context.

dataraptor-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when designing or reviewing OmniStudio DataRaptors, especially Extract versus Turbo Extract versus Transform versus Load, field mapping strategy, performance tradeoffs, and when to move work into Integration Procedures or Apex. Triggers: 'DataRaptor Extract', 'Turbo Extract', 'DataRaptor Load', 'DataRaptor Transform', 'OmniStudio data mapping'. NOT for overall OmniScript journey design or Integration Procedure sequencing when the main question is not the DataRaptor shape itself.

wire-service-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when designing or reviewing Lightning Web Components that use `@wire`, Lightning Data Service, UI API, or the GraphQL wire adapter, especially for reactive parameters, cache behavior, and refresh strategy. Triggers: 'wire service', 'refreshApex', 'reactive parameter', 'getRecord', 'wire vs imperative Apex'. NOT for component communication or generic lifecycle issues when data provisioning is not the main concern.

message-channel-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when implementing Lightning Message Service (LMS) to enable cross-DOM communication between LWC, Aura, and Visualforce components on the same Lightning page, using message channels. Triggers: 'communicate between unrelated LWC components', 'send data between Visualforce and LWC', 'lightning message service not working', 'APPLICATION_SCOPE vs default scope', 'message channel metadata deployment'. NOT for parent-child component communication (use component-communication) or server-side events.