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

      A Week In The Life Of An AI-Augmented Designer

      August 22, 2025

      This week in AI updates: Gemini Code Assist Agent Mode, GitHub’s Agents panel, and more (August 22, 2025)

      August 22, 2025

      Microsoft adds Copilot-powered debugging features for .NET in Visual Studio

      August 21, 2025

      Blackstone portfolio company R Systems Acquires Novigo Solutions, Strengthening its Product Engineering and Full-Stack Agentic-AI Capabilities

      August 21, 2025

      The best AirTag alternative for Samsung users is currently 30% off

      August 24, 2025

      One of the biggest new features on the Google Pixel 10 is also one of the most overlooked

      August 24, 2025

      I tested these viral ‘crush-proof’ Bluetooth speakers, and they’re not your average portables

      August 24, 2025

      I compared the best smartwatches from Google and Apple – and there’s a clear winner

      August 24, 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

      MongoDB Data Types

      August 23, 2025
      Recent

      MongoDB Data Types

      August 23, 2025

      Building Cross-Platform Alerts with Laravel’s Notification Framework

      August 23, 2025

      Add Notes Functionality to Eloquent Models With the Notable Package

      August 23, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      Microsoft Teams updated with a feature you probably thought already existed — “Can you hear me?” is now a thing of the past

      August 24, 2025
      Recent

      Microsoft Teams updated with a feature you probably thought already existed — “Can you hear me?” is now a thing of the past

      August 24, 2025

      Xbox Game Pass gets Gears of War: Reloaded, Dragon Age: The Veilguard, and more — here’s what is coming through the rest of August

      August 24, 2025

      Resident Evil ‘9’ Requiem has some of the most incredible lighting I’ve seen in a game — and Capcom uses it as a weapon

      August 24, 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

    Artificial Intelligence

    Scaling Up Reinforcement Learning for Traffic Smoothing: A 100-AV Highway Deployment

    August 24, 2025
    Repurposing Protein Folding Models for Generation with Latent Diffusion
    Artificial Intelligence

    Repurposing Protein Folding Models for Generation with Latent Diffusion

    August 24, 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

    Best Free and Open Source Alternatives to Apple Siri

    Linux

    Highlights from Git 2.51

    News & Updates

    Why you need a data backup plan for your Mac or PC – before disaster strikes

    News & Updates

    CVE-2025-46630 – Tenda RX2 Pro Remote Command Execution Vulnerability

    Common Vulnerabilities and Exposures (CVEs)

    Highlights

    Why the ROG Xbox Ally skips OLED—and why that’s probably a good thing

    June 16, 2025

    The newly announced ROG Xbox Ally handheld has a lot going for it. But there’s…

    CSS Grid Auto-Placement Guide

    July 12, 2025

    CVE-2025-43562 – ColdFusion OS Command Injection

    May 13, 2025

    Automate pre-sales support, capture qualified leads, and free up your team’s time for what matters most with NoForm AI – your 24/7 human-like chatbot.

    May 22, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

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