Home » Blog » How to Build a Live Chat Widget in React (Step-by-Step with Socket.IO)

How to Build a Live Chat Widget in React (Step-by-Step with Socket.IO)

To build a live chat widget in React, you need four parts: a floating chat UI made of React components, a Socket.IO server in Node.js, token-based login, and a database for message history.

This guide is for React developers and product teams who want working code, not theory. You will finish with a widget your visitors can open, type into and get live replies from.

BOSC Tech Labs has built web and mobile products for clients since 2019, and our full-stack team works with React and Node.js every day. This guide is the setup we would start a client’s chat feature with.

Each step builds on the last, from an empty project to a deployed widget that survives reconnects, slow networks and many users at once.

Key takeaways:

  • The stack: React for the UI, Socket.IO for live messages, a Node.js server, token login and a database for history.
  • Create React App is deprecated, so start new React projects with a build tool such as Vite.
  • Verify the login token in the socket handshake, or anyone can read and post messages.
  • Give every message a client-generated ID so reconnects never create duplicate messages.

What you need to build a live chat widget in React

A chat widget needs five parts: a UI visitors interact with, a real-time connection, a server that routes messages, login that identifies each person, and storage that keeps the history.

The table shows each part, the tool this guide uses for it and common alternatives.

PartWhat it doesUsed in this guideAlternatives
Chat UILauncher button, window, message list, inputReact with ViteNext.js
Real-time connectionPushes messages both ways instantlySocket.IONative WebSocket, managed chat APIs
ServerRooms, routing, broadcastingNode.js with ExpressFastify, serverless chat APIs
LoginIdentifies visitors and agentsJWT tokensServer sessions
StorageKeeps chat historyMongoDBFirebase, PostgreSQL

Every part can be swapped later, but this stack keeps the whole React chat widget in JavaScript, from the browser to the database.

One common piece of advice is now outdated: starting with Create React App. The React team deprecated Create React App in February 2025 and recommends a framework or a build tool instead.

This guide uses Vite because it starts fast and needs no extra configuration for a small widget like this one.

Step 1: Create the React app and Node.js chat server

Start with two projects: a React front end built from a starter template and a separate Node.js server running Express and Socket.IO. Keeping them apart lets you run, scale and deploy each one on its own.

Run these commands to create both projects and install their packages:

# Front end: React app
npm create vite@latest chat-widget -- --template react
cd chat-widget
npm install
npm install socket.io-client
# Back end: Node.js chat server
mkdir ../chat-server && cd ../chat-server
npm init -y
npm pkg set type=module
npm install express socket.io cors jsonwebtoken mongoose

The server uses ES modules, which is why the npm pkg set type=module line updates its package.json.

Next, create a minimal chat server. It accepts connections, puts each socket into a room per conversation and broadcasts every message to that room.

// chat-server/index.js
import express from "express";
import { createServer } from "node:http";
import { Server } from "socket.io";
import cors from "cors";
const CLIENT_ORIGIN = process.env.CLIENT_ORIGIN || "http://localhost:5173";
const app = express();
app.use(cors({ origin: CLIENT_ORIGIN }));
app.use(express.json());
const httpServer = createServer(app);
const io = new Server(httpServer, { cors: { origin: CLIENT_ORIGIN } });
io.on("connection", (socket) => {
  socket.on("join", (conversationId) => {
    socket.join(conversationId);
  });
  socket.on("message", (msg, ack) => {
    io.to(msg.conversationId).emit("message", msg);
    ack?.({ clientId: msg.clientId });
  });
});
httpServer.listen(4000, () => {
  console.log("Chat server running on http://localhost:4000");
});

A room is a named group of sockets that receive the same events. Each conversation gets its own room, so a visitor only sees messages from their own chat.

If you are new to React project setup, read our ways to start a new React app first, then come back to this step.

Step 2: Connect React to the server with Socket.IO

Socket.IO is the simplest way to add real-time chat in React: the browser keeps one open connection to your Node.js server, so new messages arrive instantly without polling or a page refresh.

First, create one shared socket for the whole app. Setting autoConnect to false means the widget connects only when a visitor opens the chat window.

// src/useChat.js
import { useEffect, useState } from "react";
import { socket } from "./socket";
export function useChat(conversationId, isOpen) {
  const [messages, setMessages] = useState([]);
  useEffect(() => {
    if (!isOpen) return;
    socket.connect();
    socket.emit("join", conversationId);
    function onMessage(msg) {
      setMessages((prev) =>
        prev.some((m) => m.clientId === msg.clientId) ? prev : [...prev, msg]
      );
    }
    socket.on("message", onMessage);
    return () => {
      socket.off("message", onMessage);
      socket.disconnect();
    };
  }, [conversationId, isOpen]);
  function sendMessage(text) {
    const msg = { clientId: crypto.randomUUID(), conversationId, text };
    setMessages((prev) => [...prev, { ...msg, pending: true }]);
    socket.emit("message", msg, (ack) => {
      setMessages((prev) =>
        prev.map((m) => (m.clientId === ack.clientId ? { ...m, pending: false } : m))
      );
    });
  }
  return { messages, sendMessage };
}

The cleanup function in useEffect matters more than it looks. Without socket.off, React Strict Mode and re-renders attach extra listeners, and every message appears twice on screen.

The hook shows each message at once with a pending flag. The server’s acknowledgement clears the flag, and the clientId check stops the room broadcast from adding the same message again.

Is Socket.IO better than plain WebSocket for chat?

For most chat widgets, yes. Socket.IO adds automatic reconnection, rooms and a fallback transport that you would otherwise build yourself on top of the browser’s WebSocket API.

This is how the two compare for a chat widget:

FeatureSocket.IOPlain WebSocket
Automatic reconnectionBuilt inYou write it
Rooms and broadcastingBuilt inYou write it
Fallback if WebSocket is blockedHTTP long-pollingNone
Extra client codeA client libraryNone (browser API)
Server requirementA Socket.IO serverAny WebSocket server

Plain WebSocket makes sense when you need the smallest client or must connect to a server you do not control. For a support widget, built-in reconnection alone usually saves more time than it costs.

Step 3: Build the React chat widget UI

The widget UI has four parts: a floating launcher button, a chat window with a header, a message list that scrolls to the newest message, and an input that sends on Enter.

This component uses the hook from Step 2 to render the React live chat widget. The hook stays mounted while the window is closed, so messages survive closing and reopening the chat.

// src/ChatWidget.jsx
import { useEffect, useRef, useState } from "react";
import { useChat } from "./useChat";
import "./ChatWidget.css";
export default function ChatWidget({ conversationId }) {
  const [isOpen, setIsOpen] = useState(false);
  const [text, setText] = useState("");
  const { messages, sendMessage } = useChat(conversationId, isOpen);
  const endRef = useRef(null);
  const inputRef = useRef(null);
  useEffect(() => endRef.current?.scrollIntoView({ behavior: "smooth" }), [messages]);
  useEffect(() => { if (isOpen) inputRef.current?.focus(); }, [isOpen]);
  function handleSend() {
    const trimmed = text.trim();
    if (!trimmed) return;
    sendMessage(trimmed);
    setText("");
  }
  if (!isOpen) {
    return (
      <button className="chat-launcher" aria-label="Open chat" onClick={() => setIsOpen(true)}>
        Chat
      </button>
    );
  }
  return (
    <div className="chat-window" role="dialog" aria-label="Chat window"
      onKeyDown={(e) => e.key === "Escape" && setIsOpen(false)}>
      <header className="chat-header">
        <span>Chat with us</span>
        <button aria-label="Close chat" onClick={() => setIsOpen(false)}>×</button>
      </header>
      <ul className="chat-messages">
        {messages.map((m) => (
          <li key={m.clientId} className={m.pending ? "pending" : ""}>{m.text}</li>
        ))}
        <li ref={endRef} />
      </ul>
      <input ref={inputRef} value={text} placeholder="Type a message"
        onChange={(e) => setText(e.target.value)}
        onKeyDown={(e) => e.key === "Enter" && handleSend()} />
    </div>
  );
}

Add styles that pin the widget to the bottom-right corner and make the window full-screen on narrow phones:

/* src/ChatWidget.css */
.chat-launcher,
.chat-window {
  position: fixed;
  right: 24px;
  bottom: 24px;
  z-index: 1000;
}
.chat-launcher { padding: 12px 18px; border-radius: 999px; }
.chat-window {
  display: flex;
  flex-direction: column;
  width: 360px;
  height: 520px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
}
.chat-messages { flex: 1; overflow-y: auto; margin: 0; padding: 12px; list-style: none; }
.chat-messages .pending { opacity: 0.5; }
@media (max-width: 480px) {
  .chat-window { inset: 0; width: auto; height: auto; border-radius: 0; }
}

A few details make the widget feel finished:

  • Focus moves to the input as soon as the window opens, so visitors can type at once.
  • The Esc key closes the window, and both buttons carry aria-label text for screen readers.
  • Pending messages stay faded until the server confirms them.
  • Visitor and agent messages look different when you compare each message’s senderId with the current user.

Keep everything in one file at first. Split it into launcher, window and message list components once the widget grows.

Step 4: Add login, message storage and chat history

Identify every visitor and agent with a signed token, verify it when the socket connects, save each message to a database, and load recent history whenever the chat window opens.

Your existing API issues a JWT after login, or a short-lived guest token for anonymous visitors. On the client, set socket.auth = { token } before calling socket.connect().

On the server, check the token during the handshake and reject the connection if it is missing or invalid:

// chat-server/auth.js
import jwt from "jsonwebtoken";
export function socketAuth(socket, next) {
  const token = socket.handshake.auth?.token;
  if (!token) return next(new Error("Authentication required"));
  try {
    // Token payload example: { id, role, conversationIds }
    socket.data.user = jwt.verify(token, process.env.JWT_SECRET);
    next();
  } catch {
    next(new Error("Invalid token"));
  }
}
export function canJoin(user, conversationId) {
  return user.role === "agent" || (user.conversationIds || []).includes(conversationId);
}

Register it with io.use(socketAuth) before the connection handler, and call canJoin in the join handler before socket.join. That check stops a logged-in visitor from joining another person’s chat.

When our engineers review a chat feature, the first thing we check is the socket handshake. If the server accepts a connection without verifying the JWT, anyone can read or post messages.

Next, save every message. A production live chat widget in React must survive page reloads, so history comes from the database, not from component state.

The model below stores messages in MongoDB and replaces the message handler from Step 1. It saves before broadcasting, and the unique clientId means a resent message is stored only once.

// chat-server/messages.js
import mongoose from "mongoose";
const messageSchema = new mongoose.Schema({
  conversationId: { type: String, index: true },
  senderId: String,
  clientId: { type: String, unique: true },
  text: String,
  createdAt: { type: Date, default: Date.now },
});
export const Message = mongoose.model("Message", messageSchema);
export function registerMessageHandler(io, socket) {
  socket.on("message", async (msg, ack) => {
    if (!socket.rooms.has(msg.conversationId)) return;
    if (typeof msg.text !== "string" || !msg.text.trim() || msg.text.length > 2000) {
      return ack?.({ clientId: msg.clientId, error: "Invalid message" });
    }
    try {
      const saved = await Message.findOneAndUpdate(
        { clientId: msg.clientId },
        { $setOnInsert: { conversationId: msg.conversationId, clientId: msg.clientId,
            text: msg.text, senderId: socket.data.user.id } },
        { upsert: true, new: true }
      );
      io.to(msg.conversationId).emit("message", saved.toObject());
      ack?.({ clientId: msg.clientId });
    } catch (err) {
      ack?.({ clientId: msg.clientId, error: "Message not saved" });
    }
  });
}

When the window opens, load the latest 50 messages through a REST endpoint protected by the same token check. Production chat also needs rate limiting; the length check above is a first limit.

If you would rather not run your own server and database, Firebase Cloud Firestore can store messages and push updates to the browser through realtime listeners.

Step 5: Add typing indicators, read receipts and agent handoff

Typing indicators and read receipts are small Socket.IO events, and agent handoff means a support agent’s dashboard joins the same conversation room as the visitor.

Send a typing event at most once every two seconds while someone types, and hide the indicator when no new event arrives within three seconds.

// src/typing.js
import { socket } from "./socket";
let lastSent = 0;
export function notifyTyping(conversationId) {
  const now = Date.now();
  if (now - lastSent > 2000) {
    socket.emit("typing", { conversationId });
    lastSent = now;
  }
}
// chat-server: relay to everyone else in the room
// socket.on("typing", ({ conversationId }) =>
//   socket.to(conversationId).emit("typing", { userId: socket.data.user.id }));

Call notifyTyping from the input’s onChange handler. On the server, socket.to() sends to everyone in the room except the sender, so nobody sees their own typing indicator.

Read receipts work the same way. When the window is open and visible, the client sends a seen event with the last message ID, and the server stores a lastReadAt time per participant.

For a customer support chat widget, new conversations go into a queue and an available agent’s dashboard joins the room. When no agent is online, switch the widget to an email form.

Step 6: Test and deploy your live chat widget in React

Before launch, test reconnection, slow networks, many users and mobile screens, then deploy the server on a host that supports long-lived WebSocket connections over HTTPS.

This checklist covers the tests worth running before launch:

TestHow to run itPasses when
ReconnectSwitch the browser to offline in DevTools, then back onlineMessages send once, with no duplicates
Slow networkThrottle the network in DevToolsSent messages show a pending state, then confirm
Many usersLoad test the server with a tool such as ArtilleryMessages keep arriving quickly and the server stays stable
Mobile screensOpen the widget on real phonesThe window fits and the keyboard does not hide the input
SecurityConnect without a tokenThe server rejects the connection

The reconnect and security rows matter most, because those failures never show up in normal office testing.

Our QA team tests real-time features on throttled mobile networks, not only office Wi-Fi. Dropped connections and duplicate messages after a reconnect are the bugs we look for first.

The duplicate fix is already in the code: the client creates a unique ID per message, the server acknowledges it, and the client ignores any message whose ID it already shows.

To deploy, follow these steps:

  1. Build the widget with npm run build and serve the files from your site or a CDN.
  2. Run the chat server behind HTTPS so the socket connects over WSS, the encrypted WebSocket protocol.
  3. If you run more than one server instance, enable sticky sessions and the Socket.IO Redis adapter so rooms work across instances.
  4. Keep the token secret and allowed origins in environment variables, never in the widget code.

Once deployed, your live chat widget in React can also run on pages that do not use React, if you bundle it as a single script that mounts itself into its own div.

Should you build or buy a live chat widget?

Build your own widget when the chat data or workflow is part of your product, use a chat SDK when you need in-app messaging fast, and use a SaaS tool when chat is only a support add-on.

The table compares the three options:

OptionTime to launchOngoing costWho owns the dataBest for
Build your ownLongest: weeks of developmentDeveloper time and hostingYouChat that is part of your product
Chat SDK or APIShorter: you build the UI on a ready backendUsage-based, often per active userThe vendor hosts itIn-app messaging, fast
SaaS live chat toolShortest: paste a scriptSubscription, often per agent seatThe vendorSupport chat on a marketing site

Owning the React chat widget means you control the data, the UI and any AI features, but your team also maintains it.

A live chat SDK handles servers and scaling while you build the UI. A hosted customer support chat widget goes live fastest, but it looks and behaves like everyone else’s.

BOSC also builds AI customer support agents, so the build-or-buy question comes up with our clients. Our usual advice: buy when chat is a support add-on, build when chat data is part of your product.

If you want an AI agent to answer first and hand over to a human, our AI customer support agents are built for that flow.

Frequently asked questions

How long does it take to build a live chat widget in React?

It depends on scope. A basic widget like the one in this guide is a small project for one developer, while a production version with login, storage, an agent dashboard and testing usually takes several weeks.

Can I build real-time chat in React without a backend?

Not fully. Browsers cannot push messages to each other directly, so you need your own server or a managed backend such as Firebase or a hosted chat API to deliver and store messages.

How much does it cost to build a chat widget?

Building your own costs developer time plus server and database hosting. Hosted tools charge a monthly fee instead, usually per agent seat or per active user, so compare the totals at your expected traffic.

Does a chat widget slow down a React website?

It can if it loads on every page view. Load the widget code with React.lazy and connect the socket only when the visitor opens the chat, and your live chat widgets in React add almost nothing to the first page load.

Can an AI agent answer chats before a human agent joins?

Yes. An AI agent trained on your help content can answer the first messages and hand the conversation, with its full transcript, to a human agent when it cannot solve the problem.

How do I add the chat widget to a website that does not use React?

Bundle the widget as one JavaScript file that creates its own div and mounts React into it. Any page can then load the widget with a single script tag, whatever framework the site uses.

Next steps: launch a chat widget your customers will use

Start with the six steps in this guide: a React project, a Socket.IO server, a widget component, token checks, saved history and a tested deployment.

A live chat widget in React stays reliable when the handshake is secured and reconnects never duplicate messages. Add agent routing or an AI agent once those basics work.

Want the chat feature built or extended by an experienced team? You can hire React developers from BOSC Tech Labs, or contact us to talk through your use case.

    Get in touch


    Explore More