0
0
ExpressHow-ToBeginner · 4 min read

How to Use WebSocket with Express: Simple Guide

To use WebSocket with Express, install the ws library and create a WebSocket server that shares the same HTTP server as Express. This allows real-time, two-way communication alongside your Express routes.
📐

Syntax

Use the ws library to create a WebSocket server. Attach it to the HTTP server created by Express. Listen for connection events and handle messages.

  • const WebSocket = require('ws'): imports the WebSocket library.
  • const wss = new WebSocket.Server({ server }): creates a WebSocket server using the existing HTTP server.
  • wss.on('connection', callback): listens for new WebSocket connections.
  • ws.on('message', callback): listens for messages from a client.
javascript
const express = require('express');
const http = require('http');
const WebSocket = require('ws');

const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });

wss.on('connection', (ws) => {
  ws.on('message', (message) => {
    console.log(`Received: ${message}`);
    ws.send(`Echo: ${message}`);
  });
});

server.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
💻

Example

This example shows a simple Express server with WebSocket support. When a client connects and sends a message, the server logs it and sends back an echo message.

javascript
const express = require('express');
const http = require('http');
const WebSocket = require('ws');

const app = express();

app.get('/', (req, res) => {
  res.send('Hello from Express with WebSocket!');
});

const server = http.createServer(app);
const wss = new WebSocket.Server({ server });

wss.on('connection', (ws) => {
  console.log('Client connected');
  ws.on('message', (message) => {
    console.log(`Received message: ${message}`);
    ws.send(`Server echo: ${message}`);
  });
  ws.send('Welcome to WebSocket server');
});

server.listen(3000, () => {
  console.log('Server listening on http://localhost:3000');
});
Output
Server listening on http://localhost:3000 Client connected Received message: Hello Server
⚠️

Common Pitfalls

Common mistakes when using WebSocket with Express include:

  • Trying to use WebSocket directly on the Express app instead of the HTTP server.
  • Not sharing the same HTTP server between Express and WebSocket, causing port conflicts.
  • Forgetting to handle connection and message events properly, leading to silent failures.
  • Not closing WebSocket connections gracefully.
javascript
/* Wrong: Creating WebSocket server without HTTP server */
const wssWrong = new WebSocket.Server({ port: 3000 });

/* Right: Share HTTP server with Express */
const server = http.createServer(app);
const wssRight = new WebSocket.Server({ server });
📊

Quick Reference

  • Install ws: npm install ws
  • Create HTTP server from Express app.
  • Attach WebSocket server to HTTP server.
  • Listen for connection and message events.
  • Send messages with ws.send().

Key Takeaways

Use the ws library to add WebSocket support to your Express HTTP server.
Attach the WebSocket server to the same HTTP server Express uses to avoid port conflicts.
Handle connection and message events to communicate with clients.
Always close WebSocket connections properly to free resources.
Test WebSocket communication with tools like browser console or WebSocket clients.