0
0
ExpressHow-ToBeginner · 4 min read

How to Use ws Library with Express for WebSocket Support

To use the ws library with express, create an HTTP server from your Express app and pass it to a new WebSocketServer instance. Then listen for WebSocket connections on that server to handle real-time communication.
📐

Syntax

Here is the basic syntax to integrate ws with express:

  • Create an Express app.
  • Create an HTTP server from the Express app.
  • Create a WebSocket server using ws and attach it to the HTTP server.
  • Listen for WebSocket connection events to handle messages.
javascript
import express from 'express';
import { createServer } from 'http';
import { WebSocketServer } from 'ws';

const app = express();
const server = createServer(app);
const wss = new WebSocketServer({ server });

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

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

Example

This example shows a simple Express server with WebSocket support using ws. When a client connects, the server sends a greeting and logs any messages received.

javascript
import express from 'express';
import { createServer } from 'http';
import { WebSocketServer } from 'ws';

const app = express();

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

const server = createServer(app);
const wss = new WebSocketServer({ server });

wss.on('connection', (ws) => {
  console.log('Client connected');
  ws.send('Welcome to WebSocket server');

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

  ws.on('close', () => {
    console.log('Client disconnected');
  });
});

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

Common Pitfalls

Common mistakes when using ws with express include:

  • Trying to use app.listen() instead of creating an HTTP server with createServer(app). The WebSocket server needs the raw HTTP server.
  • Not handling the connection event properly, so messages are not received or sent.
  • Forgetting to listen on the HTTP server instead of the Express app.
javascript
/* Wrong way: Using app.listen() directly */
import express from 'express';
import { WebSocketServer } from 'ws';

const app = express();
const wss = new WebSocketServer({ noServer: true });

app.listen(3000); // This does not expose the HTTP server for ws

wss.on('connection', (ws) => {
  ws.send('Hello');
});

/* Right way: Create HTTP server and pass to ws */
import { createServer } from 'http';

const server = createServer(app);
const wssCorrect = new WebSocketServer({ server });

server.listen(3000);
📊

Quick Reference

Key points to remember when using ws with express:

  • Use createServer(app) to get the HTTP server.
  • Pass the HTTP server to new WebSocketServer({ server }).
  • Listen for connection events on the WebSocket server.
  • Use ws.send() and ws.on('message') to communicate.
  • Start the server with server.listen(port), not app.listen().

Key Takeaways

Create an HTTP server from your Express app to use with ws.
Pass the HTTP server to the WebSocketServer constructor.
Handle WebSocket connections with the 'connection' event.
Use ws.send() to send messages and ws.on('message') to receive them.
Always listen on the HTTP server, not the Express app, for WebSocket support.