📌
Pusher
  • Pusher Support Portal
  • 📈Channels
    • Channels
      • Events
        • Does Channels Store a History Of Events And Messages?
        • Does Channels Guarantee Message Delivery to Clients?
        • How Can I Get Missed Messages After Reconnecting To Channels?
        • How Can I Enable Client Events Within My Application?
        • How Can I Implement Message (Event) History In Channels?
        • Is It Possible To Schedule Event Sending in My Channels App?
        • What Happens If I Publish Events To Channel If No Clients Are Subscribed?
        • Why Do You Require Server Authentication To Use Client Events?
        • Why Don't Channels Events Arrive In Order?
        • How Do I Trigger An Event From A Bash Shell Script?
      • Libraries
        • Does Pusher Channels work with React Native?
        • Can I Host pusher js On My Own Server?
        • Does Channels Work With My Specific Technology?
      • Limits
        • How Are Concurrent Connections Counted?
        • How Can I Add Other Contacts To My Channels Limits Notifications?
        • How Can I Configure Usage Summaries?
        • How Can I Monitor My Account Usage?
        • How Is My Message Count Calculated In Channels?
        • What Happens When I Hit My Channels Plan Limits?
        • Over What Time Period Are My Channels Limits Counted?
        • What Is The Message Size Limit When Publishing an Event in Channels?
        • Why Do My Channels Metrics Graphs and Stats Numbers Show Different Values?
        • What Is The Maximum Number of Channels Supported Per App?
      • Presence
        • How Do I See The Members Of A Presence Channel Without Appearing In It?
        • How Can I Implement Large Presence Channels On Channels?
        • Why Do Presence Channels Generate So Many Messages?
      • Subscribing
        • Providing A Custom Channels Authoriser
        • Should I Subscribe To Lots Of Channels?
        • What Does The Error 'Invalid channel name' Mean?
      • Troubleshooting
        • How Can I Perform Connectivity Diagnostics For My Version Of Pusher JS?
        • How Can I Debug My Channels Webhooks?
        • How Do I Use The Channels Debug Console And Event Creator?
        • How Does Pusher Channels Protect Against Denial Of Service Attacks?
        • My Channels Application Is Encountering An Error Code, What Does This Mean?
        • Reporting Bugs and Technical Issues
        • We Are Seeing Timeouts From The Pusher Channels API, What Can We Do?
        • What Can Cause Error '401 Unauthorized' From The Channels REST API?
        • What Does The "Unsupported event received on socket <event_name>" Error Mean?
        • What Does The 'Timestamp Expired' Response From The Channels Rest API Mean When Triggering An Event?
        • What Is Meant By Channels Error 1006?
        • What Is Meant By Channels Error 4200?
        • Why Am I Receiving "Websocket Is Closed Before The Connection Is Established" Error Messages?
        • Why Am I Receiving The 'Invalid key in subscription auth data' Error?
        • Why Am I Seeing The Error "There was a problem creating your WebHook, please try again" When Trying
        • Why Am I Receiving The "Invalid signature: Expected HMAC SHA256" Error?
        • Why Can't I Connect To Channels?
        • Why Does My Channels Event Report Error "The 'pusher' namespace is reserved for internal usage"?
        • Why Don't I Receive Notifications When My Ios Or Android Channels App Is In The Background?
        • Why Is My User Stuck In A Presence Channel?
      • Webhooks
        • Channels Webhook Timeouts and Retries
        • Can You Give Me A List Of IPs That Pusher Channels Webhooks Will Be Sent From?
        • How Can My Server Be Notified When Users Join Or Leave A Presence Channel?
        • What Is The Batch Size and Batch Window For Channels Webhooks?
        • Why Is My Server Not Receiving Webhooks Channels?
      • Connecting
        • Can You Provide Me With a List of IP Addresses that Channels Uses?
        • How Can I Manually Unsubscribe Clients From My Server?
        • Does Channels Work In Mainland China?
        • How Can I Add A Cluster Failover Process to My Channels Integration?
        • How Can I Stop Channels Users Going Offline For An Instant When They Navigate Between Pages?
        • How Can I Transition A Live App To A Different Cluster?
        • Can I use Pusher Channel Authentication with Web Framework CSRF Protection?
        • I’m Having Problems With The Reliability Of My Clients Connections To Pusher, What Can I Do?
        • Managing Channels keys in Mobile Apps
        • What Are Concurrent Channels Connections?
        • What Channels Clusters Exist?
        • What Content Security Policy (CSP) do I need for Channels?
        • What happens if a user is on a poor connection that occasionally drops? Will they miss messages?
        • What Ports Do I Need To Open In My Firewall To Allow Channels To Connect?
        • Why Am I Seeing More Channels Connections Than I Expect?
        • What WebSocket Protocols Does Channels Support?
        • How Can I Rotate My Channels App Keys
  • 🔔Beams
    • Beams
      • Libraries
        • Does Beams support React Native?
        • Ho Do I Implement Beams With A Specific Technology?
        • Does Beams have React Native support?
        • What Libraries Does Beams Support?
      • Limits
        • What Are Beams Subscribers and How Are They Counted?
        • What Happens When I Hit My Beams Plan Limits?
      • Publishing
        • How Can I Set The Time-To-Live (TTL) For a Push Notification?
        • Why Don't Fcm Notifications Trigger ‘onMessageReceived’ When In The Background State?
        • How Can I Rotate My Beams Instance Keys
      • Webhooks
        • Beams Webhook Timeouts and Retries
      • Troubleshooting
        • Can You Provide Me With A List Of IP Addressed That Beams Uses?
        • What Ports Are Required To Receive Beams Notifications On My iOS Device?
        • How Can I Migrate Between Beams Instances?
        • Why Am I Receiving Error `Push notification prompting can only be done from a user gesture` In Safar
  • 💰Account/Billing
    • Account/Billing
      • Legal
        • How Can I Comply With HIPAA When Using Pusher Channels?
        • How Can I Comply With HIPAA When Using Pusher Beams?
        • Where Can I Find Your Cookie Policy?
        • What Hosting Provider(s) And Other Subprocessors Does Pusher Use?
        • Can I Sign a DPA With Pusher
        • Does Pusher Track And Use IP Addresses?
      • Dashboards
        • How Can I Add Collaborators To My Beams Instance?
        • How Can I Add Teammates As Collaborators To My Channels App?
        • How Can I Delete My Pusher Account?
        • How Can I Reset My Password For The Pusher Dashboard?
        • How Can I Transfer App Ownership From One Channels Account To Another?
        • How Can I Transfer Instance Ownership From One Beams Account To Another?
        • How Can I Update My Channels Billing Email Address?
        • How Can I Update My Pusher Account Email Address?
      • Account Information
        • How Can I Add 2-Factor Authentication To My Pusher Account?
      • Payments / Billing
        • Can I Pay For Channels Using Amex?
        • Can I Switch To Invoice Billing For My Subscription?
        • How Can I Change The Account Name That Appears On My Channels Statement?
        • How Can I Get The Billing Statements For My Channels Account?
        • How Can I Update My Billing Details For Beams?
        • What Can I Do If My Credit Card Is Declined?
        • How Can I Update My Payment Details For Channels?
      • Plans
        • How Does My Channels Plan Level Affect The Limits Of My Apps?
        • How Can I Downgrade My Beams plan?
        • How Can I Downgrade My Channels Plan?
        • How Can I Upgrade My Beams Plan?
        • How Can I Upgrade My Channels Plan?
        • I Have Upgraded My Channels Collaborator Account Instead Of The App Owner Account, What Now?
Powered by GitBook
On this page
  1. Channels
  2. Channels
  3. Events

How Can I Implement Message (Event) History In Channels?

PreviousHow Can I Enable Client Events Within My Application?NextIs It Possible To Schedule Event Sending in My Channels App?

Last updated 1 year ago

Channels makes it really easy to add real-time data and functionality to web, mobile and IoT apps. For use cases such as notifications and signalling, that data can be transient, where the data is only relevant for a short period of time. In other cases, such as activity streams or chat, data may need to be persisted and historical data is as important as the data delivered via real-time updates.

This article covers:

  • How and when to retrieve a history of messages

For this article it is assumed that your application persists messages prior to sending them via Pusher.

There is also a tutorial that covers an example in detail. You can .

How and when to retrieve a history of messages

Being able to see a history of messages within a chat application provides context to the ongoing conversation. When you think about how you would add this functionality there are three choices that generally come to mind:

Choice
Will it work?

1. Generate static HTML for the existing messages on the server

No. Messages could be missed between the HTML being sent to the client and the subscription on the client taking place.

2. Fetch data upon connection

No. The client hasn't subscribed to the channel yet so any messages sent prior to the subscription could be missed.

3. Fetch data upon successful subscription

Yep. This way you will get any new data via Pusher and can retrieve all historical data from your server.

You should fetch the historical messages from the server after successfully subscribing to the channel. The basic flow to achieve this is:

  1. The application loads

  2. Connect to Pusher

  3. Subscribe to the channel

  4. Bind to the pusher:subscription_succeeded event on the channel

  5. Bind to the new_message event to be notified when any new chat messages arrive via Pusher

  6. Upon successful subscription, retrieve the messages from the server

  7. Add the messages to the UI, ensuring that those messages are sorted and no duplicates exist from any messages that may have come in via Pusher during the retrieval

Retrieve Missed Messages Upon Subscription

The pusher:subscription_succeeded event is emitted from at channel once Pusher has acknowledge a subscription request. It is at that point at which historical messages should be retrieved.

In the following JavaScript example a retrieveHistory handler function will be called when the subscription has succeeded:

var pusher = new Pusher(PUSHER_CHAT_APP_KEY);
var chatRoom = this.pusher.subscribe('messages');
chatRoom.bind('pusher:subscription_succeeded', retrieveHistory);

The purpose of the retrieveHistory function is to fetch messages from your server. As an example, the following code will make an AJAX call to retrieve the chat message history:

function retrieveHistory() {
  $.get('/messages').success(function(response) {
    // TODO: extract messages from the response
  });
},

In this example the /messages endpoint would need to return a number of existing messages. How it does that and how many it returns depends on your solution.

From here you need to add those messages to your application UI.

Adding Historical Messages to the UI

Now that the existing chat messages are being returned to the client they need to be shown in the UI.

When adding them to the UI it's important to check two things:

  1. That duplicates don't occur

  2. The ordering of messages in the UI is correct

The suggested solution to this is to have a sequence ID for each message so it's very easy to detect duplicates and determine the correct order of messages. If you are using a database solution, the Primary Key for each message within your database may be sufficient.

Follow Up

Now that you have an API for retrieving historic messages it is easy to implement a solution for when a client temporarily disconnects. See

Still have questions? Please reach out to our Support team by visiting .

📈
read it on the Pusher blog
How Can I Get Missed Messages After Reconnecting To Channels?
this page