Learn / Frameworks / Express / WebSockets

Express · Lesson 12 of 15

WebSockets

Upgrade an HTTP server to WebSocket and broadcast with care across processes.

  • Advanced
  • 15 min read
  • 3 objectives

Before this lessonLesson 11: Express with TypeScript

What you will learn

  • Attach a ws server
  • Broadcast a message
  • Authenticate a socket

Your Progress

0 of 15 lessons 0%

  • Lessons0 / 15
  • Completed0
  • Est. time left~ 4 hours

Create a free account to keep your progress on every device.

WebSockets are an upgrade on the same HTTP server. The ws package is small; Socket.IO adds rooms and fallbacks if you need them.

Attach to the HTTP server

import http from "node:http";
import { WebSocketServer } from "ws";
import { app } from "./app.js";

const server = http.createServer(app);
const wss = new WebSocketServer({ server, path: "/ws" });

wss.on("connection", (socket, req) => {
  socket.on("message", (raw) => {
    for (const client of wss.clients) {
      if (client.readyState === 1) client.send(String(raw));
    }
  });
});

server.listen(3000);

Auth

The browser cannot set an Authorization header on the handshake. Send a one-time ticket as a query param, or read the session cookie and verify it on connection.

Up next · Lesson 13Layered Project StructureSplit routes, services and data access so handlers stay thin.