Sub topic 5
Getting a MessageContext with @wire
This chapter assumes you can write a basic Lightning web component (LWC), that you know @wire and the connectedCallback and disconnectedCallback hooks, and that you have already deployed a message channel. The earlier chapters covered the channel metadata. Here you will learn how a component gets the MessageContext object that every publish and subscribe call needs.
What a MessageContext is
Every function in lightning/messageService that sends or receives a message takes a MessageContext as its first argument. The context tells Lightning Message Service (LMS) which component is making the call. LMS uses it for two things:
- It identifies the caller, so a subscription can be tied to the component that created it.
- It supplies the information needed to apply the default scope. Without a context, LMS can't tell which part of the page the caller belongs to.
You never build this object yourself. It is opaque, and you shouldn't read or modify its fields. You get it from the platform and pass it along.
| Function | Needs a MessageContext | Purpose |
|---|---|---|
| `publish(messageContext, channel, payload)` | Yes | Send a message |
| `subscribe(messageContext, channel, listener, options)` | Yes | Start receiving messages |
| `unsubscribe(subscription)` | No | Stop receiving, using the object `subscribe` returned |
unsubscribe takes only the subscription object. The context matters when you create the subscription.
Wiring it with @wire
MessageContext is a wire adapter, which is a data source you attach to a property or function with @wire. It takes no parameters.
import { LightningElement, wire } from 'lwc';
import { MessageContext } from 'lightning/messageService';
export default class ContextHolder extends LightningElement {
@wire(MessageContext)
messageContext;
}Two details are easy to miss:
MessageContextis imported fromlightning/messageService, not fromlwcor@salesforce/....- The decorated property receives the context object itself, not a
{ data, error }wrapper. Most adapters, such asgetRecord, deliver{ data, error }. This one doesn't, so don't writethis.messageContext.data.
The same component can use the context for both publishing and subscribing. You need only one @wire(MessageContext) property per component, however many channels it uses.
When the value is available
A wired property is populated by the framework, not by your constructor. That has two consequences.
- Don't read
this.messageContextin the constructor. It isn't set yet, so anypublishorsubscribecall there fails. - Use it from
connectedCallbackor later. The standard LMS pattern subscribes inconnectedCallbackand passesthis.messageContext.
Event handlers such as button clicks run well after the component connects, so publishing from them is safe in normal use.
Using the context to publish
This publisher passes the wired context to publish. The channel name matches the metadata from the previous chapter.
import { LightningElement, wire } from 'lwc';
import { publish, MessageContext } from 'lightning/messageService';
import RECORD_SELECTED from '@salesforce/messageChannel/RecordSelected__c';
export default class RecordList extends LightningElement {
@wire(MessageContext)
messageContext;
handleSelect(event) {
const payload = { recordId: event.currentTarget.dataset.id };
publish(this.messageContext, RECORD_SELECTED, payload);
}
}The next chapters cover publish and subscribe in detail. For now, notice that the context is the first argument in both calls and that it comes straight from the wired property.
Using the context to subscribe
A subscriber needs the same wire. Subscribing in connectedCallback works because the context is provisioned before that hook runs.
import { LightningElement, wire } from 'lwc';
import {
subscribe,
unsubscribe,
MessageContext
} from 'lightning/messageService';
import RECORD_SELECTED from '@salesforce/messageChannel/RecordSelected__c';
export default class RecordDetail extends LightningElement {
selectedId;
subscription = null;
@wire(MessageContext)
messageContext;
connectedCallback() {
if (!this.subscription) {
this.subscription = subscribe(
this.messageContext,
RECORD_SELECTED,
(message) => {
this.selectedId = message.recordId;
}
);
}
}
disconnectedCallback() {
unsubscribe(this.subscription);
this.subscription = null;
}
}This version omits the scope option. Without it, the component receives messages only while it is the active part of the page, as the scope chapter explains. The wire setup is the same either way.
Common mistakes
Most problems with the context come from using it before it exists or from treating it as something else.
| Mistake | Symptom | Fix |
|---|---|---|
| Reading `this.messageContext` in the constructor | `undefined` passed to `subscribe`, and an error from the service | Move the call to `connectedCallback` |
| Importing `MessageContext` from the wrong module | Build error or `undefined` wire adapter | Import it from `lightning/messageService` |
| Using `this.messageContext.data` | `undefined` value, and no messages are sent or received | Pass `this.messageContext` itself |
| Creating the context in a plain helper class with `@wire` | The wire never fires, because `@wire` works only in classes that extend `LightningElement` | Pass the context in from a component, or use `createMessageContext` |
| Forgetting `@wire` and writing `messageContext = MessageContext;` | The adapter function is passed instead of a context | Decorate the property with `@wire(MessageContext)` |
If you want a guard against the first mistake while debugging, check for a missing context before you call the service.
import { LightningElement, wire } from 'lwc';
import { publish, MessageContext } from 'lightning/messageService';
import RECORD_SELECTED from '@salesforce/messageChannel/RecordSelected__c';
export default class GuardedPublisher extends LightningElement {
@wire(MessageContext)
messageContext;
handleSelect(event) {
if (!this.messageContext) {
console.error('MessageContext is not available yet');
return;
}
publish(this.messageContext, RECORD_SELECTED, {
recordId: event.currentTarget.dataset.id
});
}
}In normal use this guard never fires from a click handler. Use it as a debugging aid rather than leaving it as permanent defensive code.
When @wire is not an option: createMessageContext
Sometimes the code that publishes or subscribes isn't a component class. Examples are a shared utility module or a service that several components call. @wire works only on a LightningElement, so lightning/messageService also exports two functions for managing a context by hand:
createMessageContext()returns a new context.releaseMessageContext(context)frees it.
// messageBus.js
import {
createMessageContext,
releaseMessageContext,
publish
} from 'lightning/messageService';
import RECORD_SELECTED from '@salesforce/messageChannel/RecordSelected__c';
export function publishSelection(recordId) {
const context = createMessageContext();
try {
publish(context, RECORD_SELECTED, { recordId });
} finally {
releaseMessageContext(context);
}
}Every createMessageContext call must be paired with a releaseMessageContext call. A context you create and never release stays allocated for the life of the page.
This approach has a cost, and the wire is usually the better choice:
- You take on cleanup. The wire releases its context automatically when the component is removed, and the manual one doesn't.
- A manually created context isn't tied to a component, so scope-related behavior can differ from what a component with a wired context sees. Test any subscriber that depends on scope.
- Subscriptions made with a manual context must be unsubscribed and the context released when the owner is done.
Prefer @wire(MessageContext) inside components. Reach for createMessageContext only for code outside the component model, and keep its lifetime short and explicit.
Quick reference
// Component code: let the platform manage the context.
@wire(MessageContext)
messageContext;
// Non-component code: you manage it.
const context = createMessageContext();
// ... publish(context, ...) ...
releaseMessageContext(context);Exercises
Exercise
A teammate writes console.log(this.messageContext.data) and gets undefined. What is wrong with this code, and what should they pass to publish?
Show answer
@wire(MessageContext) delivers the context object directly, not a { data, error } wrapper, so there is no data property. They should pass this.messageContext itself as the first argument to publish.
Exercise
A component calls subscribe(this.messageContext, CHANNEL, handler) inside its constructor and fails. Why, and where should the call go?
Show answer
The wired property is provisioned by the framework after the instance is created, so this.messageContext is not set in the constructor. Move the call to connectedCallback, which runs after the context is available.
Exercise
Why must a utility module that calls createMessageContext also call releaseMessageContext, and when is that not needed?
Show answer
A manually created context is not released automatically, so skipping releaseMessageContext leaves it allocated for the life of the page. It is not needed when the component uses @wire(MessageContext), because the framework releases that context when the component is removed.