WebSocket with Express.js — Complete Guide
In this tutorial, you will learn about Websocket with Express.js"Express" >}}.js. We cover key concepts, practical examples, and best practices to help you master this topic.
Express.js and WebSocket share the same HTTP server, enabling HTTP routes and WebSocket endpoints on the same port. This simplifies deployment, session management, and authentication by sharing the Express middleware pipeline.
What You'll Learn
- Combining Express HTTP routes with WebSocket
- Sharing Express sessions with WebSocket connections
- Using Express middleware for WebSocket auth
- Serving web pages alongside real-time APIs
- Graceful shutdown of both servers
Why It Matters
Running HTTP and WebSocket on the same port simplifies deployment (one port, one TLS certificate). Shared sessions let WebSocket connections authenticate using existing Express session data.
Real-World Use
Many applications use Express for REST endpoints and Socket.IO for real-time updates on the same server. This pattern is common in monolithic real-time applications.
flowchart LR
Client[Client] -->|HTTP Request| Express[Express App]
Client -->|WebSocket Upgrade| WSS[WebSocket Server]
Express --> Shared[Shared HTTP Server]
WSS --> Shared
Shared --> Port[Single Port: 3000]
Teacher Mindset
Create a single HTTP server and attach both Express and WebSocket to it. The HTTP server handles the upgrade handshake for WebSocket. Use the same port, TLS settings, and session middleware.
Code Examples
// Example 1: Express + ws on the same server
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 });
// Express routes
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
// WebSocket server
wss.on('connection', (ws, req) => {
console.log('WebSocket client connected from:', req.url);
ws.on('message', (data) => {
// Broadcast to all WebSocket clients
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(data);
}
});
});
});
server.listen(3000, () => {
console.log('HTTP + WebSocket on port 3000');
});
// Example 2: Express + Socket.IO
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = new Server(server);
app.use(express.static('public'));
app.get('/api/status', (req, res) => {
res.json({
connections: io.engine.clientsCount
});
});
io.on('connection', (socket) => {
socket.on('message', (data) => {
io.emit('message', data);
});
});
server.listen(3000);
// Example 3: Session sharing with Express and WebSocket
const session = require('express-session');
const sessionMiddleware = session({
secret: 'your-secret',
resave: false,
saveUninitialized: true
});
app.use(sessionMiddleware);
// Share session with WebSocket
wss.on('connection', (ws, req) => {
// Run the session middleware manually
sessionMiddleware(req, {}, () => {
const userId = req.session.userId;
console.log('Authenticated user:', userId);
ws.userId = userId;
});
});
Common Mistakes
- Creating separate ports for HTTP and WebSocket instead of sharing one
- Not sharing the session middleware between Express and WebSocket
- Starting the Express app without creating an HTTP server (app.listen creates one internally)
- Not handling the case where the upgrade request matches an Express route
- Forgetting to call server.close() on shutdown
Practice
- Create an Express app with a /health route.
- Add ws WebSocket server on the same port.
- Serve an HTML page that connects to the WebSocket.
- Share Express session data with the WebSocket handler.
- Challenge: Build a real-time admin dashboard where Express serves the page and WebSocket streams metrics.
FAQ
Mini Project
Build an application with Express serving a dashboard page and WebSocket streaming real-time server metrics (CPU, memory, connections). Use the same port. Share Express session data for WebSocket authentication.
What's Next
Next, you will learn about Django Channels for WebSocket in Python.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro