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

      Anthropic proposes transparency framework for frontier AI development

      July 8, 2025

      Sonatype Open Source Malware Index, Gemini API Batch Mode, and more – Daily News Digest

      July 8, 2025

      15 Top Node.js Development Service Providers for Large Enterprises in 2026

      July 8, 2025

      Droip: The Modern Website Builder WordPress Needed

      July 8, 2025

      The gaming headset I use every day is slashed to its lowest price ever thanks to Amazon Prime Day — “stellar battery life” awaits

      July 9, 2025

      How passkeys work: The complete guide to your inevitable passwordless future

      July 9, 2025

      This Sony OLED TV is my pick for best Prime Day deal – and it’s the last chance to get 50% off

      July 9, 2025

      Blizzard announces release date for World of Warcraft: The War Within’s 3rd major content patch — a patch that will feature the largest, city-sized raid boss in MMORPG history

      July 8, 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

      Top PHP Projects for B.Tech Students: Learn Real Skills with PHPGurukul Projects

      July 8, 2025
      Recent

      Top PHP Projects for B.Tech Students: Learn Real Skills with PHPGurukul Projects

      July 8, 2025

      Deno 2.4: deno bundle is back

      July 8, 2025

      From Silos to Synergy: Accelerating Your AI Journey

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

      The gaming headset I use every day is slashed to its lowest price ever thanks to Amazon Prime Day — “stellar battery life” awaits

      July 9, 2025
      Recent

      The gaming headset I use every day is slashed to its lowest price ever thanks to Amazon Prime Day — “stellar battery life” awaits

      July 9, 2025

      Blizzard announces release date for World of Warcraft: The War Within’s 3rd major content patch — a patch that will feature the largest, city-sized raid boss in MMORPG history

      July 8, 2025

      Microsoft recently raised the price of the Xbox Series S, but these retailers just dropped it back down again — close to the old price, but not for long

      July 8, 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

    Common Vulnerabilities and Exposures (CVEs)

    CVE-2025-49697 – Microsoft Office Heap Buffer Overflow Vulnerability

    July 9, 2025
    Common Vulnerabilities and Exposures (CVEs)

    CVE-2025-49701 – Microsoft Office SharePoint Cross-Site Scripting (XSS)

    July 9, 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

    Facteur is mail-merge software

    Linux

    CVE-2025-47814 – GNU PSPP Zip-Reader Heap-Based Buffer Overflow

    Common Vulnerabilities and Exposures (CVEs)

    Trust but Verify: The Curious Case of AI Hallucinations

    Development

    CVE-2025-3634 – Moodle Authentication Bypass

    Common Vulnerabilities and Exposures (CVEs)

    Highlights

    10 Best PC Games Under 2 GB to Install and Play

    July 4, 2025

    Best PC games under 2 GB offer compact yet compelling gameplay experiences ideal for SSD-sensitive setups…

    The best Minecraft game is free on Amazon Prime

    April 5, 2025

    UNC1151 Exploits Roundcube Flaw in Spear Phishing Attack

    June 9, 2025

    How to Turn Ubuntu 24.04 into a KVM Hypervisor – Quick Setup with Web Management

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

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