How do you implement WebSocket support alongside Express.js?
Answer
Express handles HTTP, but you can add WebSocket support by sharing the HTTP server. The most common approach uses Socket.io: const server = require('http').createServer(app); const io = require('socket.io')(server); io.on('connection', socket => { socket.on('message', data => io.emit('message', data)); }); server.listen(3000);. Both HTTP (Express) and WebSocket (Socket.io) connections are handled on the same port. Alternatively, use the ws package for raw WebSocket support without the Socket.io abstraction. WebSocket connections are persistent bidirectional channels — unlike HTTP, the server can push data to clients at any time. Use cases: real-time chat, live notifications, collaborative editing.
Previous
What is Express.js Router-level middleware?
Next
What are security best practices for Express.js APIs?
More Express.js Questions
View all →- Advanced What are security best practices for Express.js APIs?
- Advanced How does clustering work in Node.js/Express for better performance?
- Advanced What is the difference between Express 4.x and Express 5.x?
- Advanced How do you implement a graceful shutdown in Express.js?
- Advanced How do you implement request tracing and correlation IDs in Express?