Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      Sunshine And March Vibes (2025 Wallpapers Edition)

      May 22, 2025

      The Case For Minimal WordPress Setups: A Contrarian View On Theme Frameworks

      May 22, 2025

      How To Fix Largest Contentful Paint Issues With Subpart Analysis

      May 22, 2025

      How To Prevent WordPress SQL Injection Attacks

      May 22, 2025

      Sam Altman says ChatGPT’s viral Ghibli effect “forced OpenAI to do a lot of unnatural things”

      May 22, 2025

      How to get started with Microsoft Copilot on Windows 11

      May 22, 2025

      Microsoft blocks employees from sending emails that mention “Palestine” or “Gaza”

      May 22, 2025

      I missed out on the Clair Obscur: Expedition 33 Collector’s Edition but thankfully, the developers are launching something special

      May 22, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      Perficient is Shaping the Future of Salesforce Innovation

      May 22, 2025
      Recent

      Perficient is Shaping the Future of Salesforce Innovation

      May 22, 2025

      Opal – Optimizely’s AI-Powered Marketing Assistant

      May 22, 2025

      Content Compliance Without the Chaos: How Optimizely CMP Empowers Financial Services Marketers

      May 22, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      Sam Altman says ChatGPT’s viral Ghibli effect “forced OpenAI to do a lot of unnatural things”

      May 22, 2025
      Recent

      Sam Altman says ChatGPT’s viral Ghibli effect “forced OpenAI to do a lot of unnatural things”

      May 22, 2025

      How to get started with Microsoft Copilot on Windows 11

      May 22, 2025

      Microsoft blocks employees from sending emails that mention “Palestine” or “Gaza”

      May 22, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»How to Add Live Chat to Your Applications with Rocket.chat

    How to Add Live Chat to Your Applications with Rocket.chat

    April 7, 2025

    The fastest way to gather valuable information about your site’s users is still by talking to them. And what better way to do this than by adding a chat system to your app?

    For my case, I just wanted to add a chat system to my portfolio website so I could get valuable info from potential employers and clients. I ended up building something like this:

    Live chat demo screenshot

    Table of Contents

    1. Why Rocket.Chat, you may ask?

    2. Prerequisites

    3. Getting Started

      • Step 1: Set Up the Rocket.Chat Server

      • Step 2: Configure the Rocket.Chat Server

      • Step 3: Register the Visitor

        • How to Register the Visitor

        • How to Create or Retrieve the Chat Room

        • How to Retrieve Livechat Configuration

      • Step 4: Create the Connection to WebSocket

    4. Conclusion

    Why Rocket.Chat, you may ask?

    Rocket.Chat is a great option because:

    • Open Source: It’s free and customizable.

    • Comprehensive APIs: Their APIs make integration simple.

    • Flexible Hosting: Self-host your own or use their cloud version with a free trial (which we’ll use here).

    Prerequisites

    Before you continue, there are a few things you should know and have:

    • A running Rocket.Chat server (either self-hosted or on Rocket.Chat Cloud). Here, I’ll show you how to set up one with Rocket.Chat Cloud.

    • A working knowledge of JavaScript fundamentals.

    Getting Started

    First things first, let’s set up a Rocket.Chat server. Again, you can either self host your own or use their cloud version. And don’t worry – you don’t have to pay anything right now or for this tutorial, as they provide a 30 day free trial.

    Step 1: Set Up the Rocket.Chat Server

    Head over to https://cloud.rocket.chat and create your free account.

    Once you’re logged in, click on the “Change to SaaS trial” button to launch a cloud-hosted server.

    Change to SaaS trial button

    Next, create a Cloud Workspace by providing your workspace name, URL, and server region.

    Rocket.Chat Cloud Workspace screenshot

    It will take a little while to set up. When it’s done, you should see something similar to this:

    Rocket.Chat dashboard screenshot

    Now copy your server URL—it should look like this: https://example.rocket.chat.

    Step 2: Configure the Rocket.Chat Server

    Before diving into the code, we need to configure our server so we can use the livechat API.

    To start, open your Rocket.Chat server and click on the menu button, then click on Omnichannel.

    Rocket.Chat Omnichannel menu screenshot

    Click on Agents on the sidebar and add yourself as an agent.

    Rocket.Chat Omnichannel Agents section screenshot

    Next, click on Departments and create a Department. I’ll call mine Chats.

    Rocket.Chat Omnichannel Departments section screenshot

    Now you need to configure a few things about the Livechat widget:

    • Make sure you turn on the offline form and set the Email Address to Send Offline Messages.

    • Also, configure your business hours to the times you’ll be available.

    Step 3: Register the Visitor

    Next, we need to register the visitor and create a room for them. To do this, you need to collect the visitor’s name and email and generate a random unique ID.

    How to Register the Visitor

    First, we need to register the visitor in the server. We need their name, email, and token. You send those to this endpoint: /api/v1/livechat/visitor. Here’s an example code that you might send from your backend:

    const body = {
      name: "Visitor Name",          // Replace with the visitor's name
      email: "visitor@example.com",  // Replace with the visitor's email
      token: "unique-visitor-token"  // Replace with a generated unique token
    };
    
    fetch(`${process.env.ROCKETCHAT_URL}/api/v1/livechat/visitor`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Cache-Control': 'no-cache'
      },
      body: JSON.stringify(body)
    })
      .then(response => response.json())
      .then(data => {
        if (data.success) {
          console.log("Visitor registered:", data);
        } else {
          console.error("Visitor registration failed:", data);
        }
      })
      .catch(error => console.error("Error in visitor registration:", error));
    

    How to Create or Retrieve the Chat Room

    After you’ve registered the visitor, you need to create a room for them so they can send you messages and you can respond.

    Call this endpoint /api/v1/livechat/room with the visitor token as a query parameter. If the visitor already has a room, it’ll be returned. If not, a new one will be created. This is how you can make that request from your backend:

    const token = "unique-visitor-token"; // Replace with the actual visitor token
    
    fetch(`${process.env.ROCKETCHAT_URL}/api/v1/livechat/room?token=${token}`, {
      method: 'GET',
      headers: { 'Content-Type': 'application/json' },
    })
      .then(response => response.json())
      .then(data => {
        if (data.success) {
          console.log("Room retrieved:", data);
        } else {
          console.error("Failed to retrieve room:", data);
        }
      })
      .catch(error => console.error("Error in retrieving room:", error));
    

    How to Retrieve Livechat Configuration

    Lastly, we need to get the info about the visitor and the agent we registered. Use this API endpoint to get the visitor token, room ID, and agent info. You can use it to check if the agent is online before trying to connect to the WebSocket.

    const token = "unique-visitor-token"; // Replace with the actual visitor token
    const url = `${process.env.ROCKETCHAT_URL}/api/v1/livechat/config?token=${token}`;
    
    fetch(url, {
      method: 'GET',
      headers: { 'Content-Type': 'application/json' },
    })
      .then(response => response.json())
      .then(data => {
        if (data.success) {
          console.log("Livechat config:", data);
        } else {
          console.error("Failed to get livechat config:", data);
        }
      })
      .catch(error => console.error("Error fetching livechat config:", error));
    

    Step 4: Create the Connection to WebSocket

    To establish the live chat experience, we need to open a WebSocket connection to Rocket.Chat and handle messaging.

    WebSocket Connection Example

    First, open the WebSocket like this:

    const rocketChatSocket = new WebSocket("ws://example.rocket.chat/websocket");
    

    Then connect:

    const connectRequest = {
      msg: "connect",
      version: "1",
      support: ["1", "pre2", "pre1"]
    };
    rocketChatSocket.send(JSON.stringify(connectRequest));
    

    You can keep the connection alive by responding to the server’s "ping" messages with a "pong".

    rocketChatSocket.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        if (data.msg === "ping") {
          console.log("Received ping from server, sending pong");
          rocketChatSocket.send(JSON.stringify({ msg: "pong" }));
        }
      } catch (error) {
        console.error("Error parsing WebSocket message:", error);
      }
    };
    

    You can subscribe to the room created for the visitor. Just use the visitor’s token and room ID from the previous sections.

    const subscribeRequest = {
      msg: "sub",
      id: "unique-subscription-id", // Replace with your unique ID
      name: "stream-room-messages",
      params: [
        "fetched-room-id", // Replace with the room ID variable
        {
          useCollection: false,
          args: [
            { visitorToken: "visitor-token" } // Replace with your visitor token variable
          ],
        },
      ],
    };
    rocketChatSocket.send(JSON.stringify(subscribeRequest));
    

    You can also listen for incoming messages. Here’s how you can process new messages as they arrive:

    rocketChatSocket.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        if (
          data.msg === "changed" &&
          data.collection === "stream-room-messages"
        ) {
          // Handle new messages
          if (data.fields && data.fields.args && data.fields.args.length > 0) {
            const newMessage = data.fields.args[0];
            // Assume isValidChatMessage is defined to validate the message format
            if (isValidChatMessage(newMessage)) {
              // Update your messages list here
              console.log("New message received:", newMessage);
            }
          }
        }
      } catch (error) {
        console.error("Error parsing WebSocket message:", error);
      }
    };
    

    What if you want to send livechat messages? Just use this code to do so:

    const sendMessageRequest = {
      msg: "method",
      method: "sendMessageLivechat",
      params: [
        {
          _id: "unique-message-id",  // Replace with a generated unique ID for the message
          rid: "room-id",            // Replace with the actual room ID
          msg: "Your message here",  // Replace with the message text you want to send
          token: "visitor-token"     // Replace with the actual visitor token
        }
      ],
      id: "unique-request-id"        // Replace with a unique request ID
    };
    
    rocketChatSocket.send(JSON.stringify(sendMessageRequest));
    

    In your actual implementation, you can integrate these examples into your backend or client-side logic as needed.

    You can take a look at the source code for how I implemented mine with Next.js or you can look at the live demo.

    Conclusion

    Adding a Livechat feature to your web apps shouldn’t be hard. With Rocket.Chat’s livechat API, you can quickly integrate chat functionality and gain valuable insights from your users. I even built an SDK wrapper to make it easier to use.

    Now it’s your turn! Try out Rocket.Chat’s API and build your own live chat system. You can explore more in the Rocket.Chat documentation.

    Happy coding!

    Source: freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More 

    Hostinger
    Facebook Twitter Reddit Email Copy Link
    Previous ArticleYour Android phone just got a major Gemini upgrade for free – Samsung models included
    Next Article It only took Call of Duty: Warzone going back in time to make the game so much better — to the point even I enjoy it now

    Related Posts

    Security

    Nmap 7.96 Launches with Lightning-Fast DNS and 612 Scripts

    May 23, 2025
    Common Vulnerabilities and Exposures (CVEs)

    CVE-2025-47512 – Tainacan Path Traversal

    May 23, 2025
    Leave A Reply Cancel Reply

    Hostinger

    Continue Reading

    DeepMind CEO claims Google has the “ingredients” to maintain AI lead over DeepSeek’s “exaggerated” success — after Microsoft CEO Satya Nadella said Google already missed the opportunity to be the “default winner”

    News & Updates

    5 ways to get more out of your WearOS smartwatch

    Development

    Distribution Release: siduction 2024.1.0

    Development

    CVE-2025-47710 – Drupal Enterprise MFA – TFA Authentication Bypass

    Common Vulnerabilities and Exposures (CVEs)

    Highlights

    Exploring Anime.js: A Powerful JavaScript Animation Library

    March 17, 2025

    Post Content Source: Read More 

    Meta claims Threads racked up 175 M monthly active users, but it does not tell the full picture

    July 5, 2024

    6 Best Bank Reconciliation Software in 2025

    March 18, 2025

    The Curse of Tunko Caviya

    March 23, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.