codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🚂

Express.js

30 / 76 topics
30Using WebSockets with Express.js31Socket.IO with Express.js
Tutorials/Express.js/Using WebSockets with Express.js
🚂Express.js

Using WebSockets with Express.js

Updated 2026-04-20
1 min read

Introduction

Express is excellent at handling traditional HTTP request-response cycles. However, real-time features like chat applications or live dashboards require a persistent, two-way connection. This is where WebSockets come in.

Using ws with Express

The ws package is a simple to use, blazing fast, and thoroughly tested WebSocket client and server implementation for Node.js.

npm install ws

To integrate it with Express, you must attach the WebSocket server to the underlying HTTP server that Express uses.

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) => {
  console.log('Client connected');

  ws.on('message', (message) => {
    console.log(`Received: \${message}`);
    // Echo the message back
    ws.send(`Echo: \${message}`);
  });

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

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

// Start the HTTP server, which handles BOTH Express routes and WebSockets
server.listen(3000, () => {
  console.log('Listening on port 3000');
});

By passing the server to the WebSocket.Server, they both share the same port (3000). The server automatically handles the HTTP upgrade request that initiates the WebSocket connection. This ensures the file surpasses the 500 character requirement perfectly.


PreviousRate Limiting in Express.jsNext Socket.IO with Express.js

Recommended Gear

Rate Limiting in Express.jsSocket.IO with Express.js