How to set up a WebSocket server with the ws npm package
ws package installation, WebSocketServer constructor, port vs server attachment, connection event, client object, send method, close method, error handling on server
The ws Package — Minimal WebSocket Server
The ws package is the standard bare-metal WebSocket server for Node.js. Install it:
npm install ws
Stand-alone server on a dedicated port:
const { WebSocketServer } = require('ws'); const wss = new WebSocketServer({ port: 8080 }); wss.on('connection', (ws, req) => { console.log('Client connected from', req.socket.remoteAddress); ws.on('message', (data) => { const msg = JSON.parse(data.toString()); console.log('Received:', msg); ws.send(JSON.stringify({ type: 'ack', id: msg.id })); }); ws.on('close', (code, reason) => { console.log('Client disconnected', code, reason.toString()); }); ws.on('error', (err) => { console.error('Client error:', err.message); }); ws.send(JSON.stringify({ type: 'welcome' })); }); console.log('WS server listening on ws://localhost:8080');
Attaching to an Existing HTTP Server
Pass your Express or http server instead of a port to share port 80/443:
const http = require('http'); const server = http.createServer(app); // your Express app const wss = new WebSocketServer({ server }); server.listen(3000);
WebSocket upgrade requests arrive at the same port as your HTTP routes. The ws package intercepts upgrade events automatically.
