Node.js
WebSocket
Write the realtime layer with WebSocket.
The WebSocket layer
In this lesson we add a WebSocket layer to the skeleton for real-time communication. We will define a simple io object and attach it to the Express app. In a real project, Socket.io is used.
Example: const io = { on: () => {} }; io.on("connection", (socket) => { console.log("Client connected"); });. This is the skeleton of the real-time layer. In production io = socketIo(server). The skeleton's goal is to show how a WebSocket is added to the app. WebSocket is separate from the Express route layer; it listens to different events. Express handles HTTP requests, WebSocket handles real-time events.
WebSocket setup
The WebSocket runs alongside the Express app. Express handles HTTP requests; the WebSocket listens to real-time events. Both live in a single server.
Example: const io = socketIo(server); io.on("connection", (socket) => { socket.on("chat", (message) => { io.emit("chat", message); }); });. This is the real-time chat flow. The client connects, sends a chat event, the server broadcasts it to all clients. The WebSocket manages a separate event loop from Express, but it runs in the same Node.js process. This lets a single port serve both HTTP and real-time.
Exercise Add the WebSocket layer
Add const io = { on: () => {} } to the skeleton below. Print "WebSocket ready" with console.log.
Show example solution
const express = require("express");
const app = express();
app.get("/", (req, res) => res.json({ status: "ok" }));
const db = { ready: true };
app.get("/db", (req, res) => res.json({ db: db.ready }));
const io = { on: () => {} };
console.log("WebSocket ready");
Test yourself
-
Match each piece to its role
- express
- HTTP requests
- io
- Real-time events
- app.get
- Defines a route
- io.on
- Listens to connections
-
What events does the WebSocket handle?
io.on("connection", (socket) => {})
- Real-time events
- HTTP requests
- CSS styles
- File backups
Show answer
Real-time events — The WebSocket handles real-time events.
-
Complete the io.on call
io.____("connection", (socket) => {});
Show answer
io.on("connection", (socket) => {});
Next lesson: Security