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

      CodeSOD: A Unique Way to Primary Key

      July 22, 2025

      BrowserStack launches Figma plugin for detecting accessibility issues in design phase

      July 22, 2025

      Parasoft brings agentic AI to service virtualization in latest release

      July 22, 2025

      Node.js vs. Python for Backend: 7 Reasons C-Level Leaders Choose Node.js Talent

      July 21, 2025

      The best CRM software with email marketing in 2025: Expert tested and reviewed

      July 22, 2025

      This multi-port car charger can power 4 gadgets at once – and it’s surprisingly cheap

      July 22, 2025

      I’m a wearables editor and here are the 7 Pixel Watch 4 rumors I’m most curious about

      July 22, 2025

      8 ways I quickly leveled up my Linux skills – and you can too

      July 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

      The Intersection of Agile and Accessibility – A Series on Designing for Everyone

      July 22, 2025
      Recent

      The Intersection of Agile and Accessibility – A Series on Designing for Everyone

      July 22, 2025

      Zero Trust & Cybersecurity Mesh: Your Org’s Survival Guide

      July 22, 2025

      Execute Ping Commands and Get Back Structured Data in PHP

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

      A Tomb Raider composer has been jailed — His legacy overshadowed by $75k+ in loan fraud

      July 22, 2025
      Recent

      A Tomb Raider composer has been jailed — His legacy overshadowed by $75k+ in loan fraud

      July 22, 2025

      “I don’t think I changed his mind” — NVIDIA CEO comments on H20 AI GPU sales resuming in China following a meeting with President Trump

      July 22, 2025

      Galaxy Z Fold 7 review: Six years later — Samsung finally cracks the foldable code

      July 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 

    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

    Development

    GPT-5 is Coming: Revolutionizing Software Testing

    July 22, 2025
    Development

    Win the Accessibility Game: Combining AI with Human Judgment

    July 22, 2025
    Leave A Reply Cancel Reply

    For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

    Continue Reading

    CVE-2024-13955 – Aspect SQL Injection Vulnerability

    Common Vulnerabilities and Exposures (CVEs)

    CVE-2025-40777 – ” BIND Named CNAME Chain Abort Vulnerability”

    Common Vulnerabilities and Exposures (CVEs)

    Miracle-WM 0.6 Released with Further Refinements

    Linux

    Windows 11’s new update system is a brutal reminder of where the Microsoft Store falls short

    News & Updates

    Highlights

    News & Updates

    Seagate’s 2TB Expansion Card for the Xbox Series X|S is almost down to its lowest ever price, so now is very much the time to buy

    April 3, 2025

    If you don’t have a storage expansion card for your Xbox Series console yet, you…

    Marvel Rivals is bringing a wave of swimsuits this summer

    April 18, 2025

    I love that transparent technology is making a comeback — and one of the biggest gaming companies has joined the fun

    June 21, 2025

    Bring back the fun with p5.js 2.0

    April 25, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

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