Lightning Web Component and Streaming API

Reading Time: 3 minutes

Streaming API and Lightning Web Component

1. Features

  • Subscribe Push Topics, Platform Events.
  • Easy to use LWC APIs.
  • Easier control to subscribe, unsubscribe and check the status of the subscription.
  • This component can be used in the Lightning(Aura) Component as well.

2. Introduction

LWC Streaming API component let you subscribe streaming API channel in an easy way. You just need to provide the channel name. Its onmessage event let you get the payload from streaming API.



This component has three types of attributes.

  1. channel: This is a required attribute. We need to define the channel name in this attribute. Ex: /topic/NewContactCreated and event/My_Event__e.
  2. api-version: This is an optional attribute. It tells that which API version will be used for cometd. If you omit this then it will take 45.0 as the default version.
  3. debug: This is an optional attribute. It takes the boolean value as the parameter. It allows you to see various logs on browser console. By default, this is set to false if you omit this.


This component has two types of events.

  1. onmessage: This event gets fired when any streaming API sends the payload/message. You need to define the handler for your component to get the value from this event. You can get payload using this: event.detail.payload
  2. onerror: This event fire if any kind of error happens at the LWC streaming API component. You need to define the handler for your component to get the error message from this event. You can get the error using this: event.detail.error

Note: You can define debug=true to see all the console results as well.


This component has three types of methods that you can use to re-subscribe, unsubscribe and check the status of the subscription. By default when component rendered get completed, it subscribes to the streaming channel.

  1. subscribe(): Subscribe the channel if it was destroyed or unsubscribe. You cannot Subscribe a channel if it already Subscribed. Multiple subscriptions will send multiple payload event from the streaming API.
  2. unsubscribe(): It unsubscribes the channel. You can subscribe to a channel if it is unsubscribed. We can use this to stop receiving payloads.
  3. checkConnection(): This method returns true or false. If the channel is subscribed then it will return the true else false.

3. Demo Video


4. Example Code

Deploy the code of streaming API from Github using deploy to Salesforce button. As this repo is already in sfdx format, you can directly use with scratch orgs by cloning it to local.

Step 1. Create a push topic using the Developer Console. Copy the following code and execute in the developer console. What will it do? It will create a push topic name NewContactCreated. Whenever a contact record gets created. It will send the payload to the onmessage event. Read PushTopic Events from salesforce document.

PushTopic pushTopic = new PushTopic();
pushTopic.Name = 'NewContactCreated';
pushTopic.Query = 'select Id,Name from Contact';
pushTopic.ApiVersion = 45.0;
pushTopic.NotifyForOperationCreate = true;
pushTopic.NotifyForOperationUpdate = false;
pushTopic.NotifyForOperationUndelete = false;
pushTopic.NotifyForOperationDelete = false;
pushTopic.NotifyForFields = 'All';
insert pushTopic;

Step 2. Create a Lightning Web Component name as lwc_streaming_demo. Copy and paste the following code to the files.

Note: Add the target configuration in the meta XML file. so you can add your demo component to the using the app builder. In my case, I have added the component to the home page.


import { LightningElement,track } from 'lwc';

export default class Lwc_streaming_demo extends LightningElement {

    @track error = '';
    @track payload = '';
    @track isConnectionOn;

    //Handles the error
        //Error is coming in the event.detail.error
        this.error = JSON.stringify(event.detail.error);

    //Handles the message/payload from streaming api
        //Message is coming in event.detail.payload
        this.payload = this.payload + JSON.stringify(event.detail.payload);

    //This method is subscribing the channel

    //This method is unsubscribing the channel

        this.payload = '';
        this.error = '';

    //This method is checking if the channel is subscribed or not
        this.isConnectionOn = this.template.querySelector('.lwc_streaming_api-1').checkConnection();



    <lightning-button label="Destroy Connection"  onclick={destroy}></lightning-button>

    <lightning-button label="Restart Connection"  onclick={restart}></lightning-button>

    <lightning-button label="Check Connection"  onclick={checkConnection}></lightning-button>

    <div style="background: white;padding: 50px;">
        <div style="margin:20px;">
        <div style="margin:20px;">

        <div style="margin:20px;">
            Is Connection On:


<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="" fqn="lwc_streaming_demo">

Step 3. Open your demo component. Now create some contact records and you will see the message/payload on the screen.

Step 4 (Another way to use): If you want to try it with platform events. Create a platform event object. Subscribe it using below code.


Here Test_Event__e is my platform event object name.

Now create platform event records using below code:

Test_Event__e te = new Test_Event__e ();
te.Test_Field__c  = 'test data';
Database.SaveResult sr = EventBus.publish(te);

I have used a custom text field (Test_Field__c) in the platform event.

Get Above code from the gist.

5. Resources

  1. Github Repository 
  2. Streaming API Salesforce Document

Leave a Reply