CodeBlanks Logo Icon CodeBlanks

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.

Practice Add the WebSocket layer

Add const io = { on: () => {} } to the skeleton below. Print "WebSocket ready" with console.log.

Starter code

index.js
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 }));
// add io here
// write here
// Print "WebSocket ready"
// write here

Sample solution

index.js
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");

Expected output

WebSocket ready

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each piece to its role

Term Meaning
express HTTP requests
io Real-time events
app.get Defines a route
io.on Listens to connections

2 What events does the WebSocket handle?

index.js
io.on("connection", (socket) => {})
  • Real-time events Correct answer
  • HTTP requests
  • CSS styles
  • File backups

Explanation: The WebSocket handles real-time events.

3 Complete the io.on call

Question
io.____("connection", (socket) => {});
Answer
io.on("connection", (socket) => {});

Explanation: io.on listens to connections.

All lessons in Advanced