Vanilla JavaScript Projects

Project 39, Media and real-time

Live Chat App

Open two tabs and chat between them right away. Run the tiny included server and people on other phones and laptops can join the same rooms.

Main API
WebSocket
No-server mode
BroadcastChannel
Files
index.html, server.js
Your browser
Checking

Chat

Tabs on this device

How it works

  1. Pick a transportWith no server address, messages go over BroadcastChannel between tabs. With one, they go over a WebSocket.
  2. Send eventsMessages, typing, joins and reactions are small JSON events with a room name and a sender id.
  3. RenderEach tab applies events to its local state and redraws the room. The server only relays events, it keeps nothing.
const ws = new WebSocket("wss://chat.example.com");
ws.onmessage = (e) => handle(JSON.parse(e.data));

function send(type, data) {
  ws.send(JSON.stringify({ type, room, from: me.id, name: me.name, ...data }));
}
input.addEventListener("input", throttle(() => send("typing"), 1500));
form.addEventListener("submit", () => send("message", { text: input.value, id: crypto.randomUUID() }));
// server.js relays every message to everyone else
wss.on("connection", (s) => s.on("message", (d) => wss.clients.forEach((c) => c !== s && c.send(d.toString()))));