WebSockets in Node.js
๐ Covered in this chapter:
Real-Time Communication ยท Socket Connections ยท Sending/Receiving Messages ยท Rooms
Add real-time, bidirectional communication to your Node.js app using WebSockets โ the foundation of chat apps and live notifications.
1WebSockets in Node.js โ What You'll Learn
Add real-time, bidirectional communication to your Node.js app using WebSockets โ the foundation of chat apps and live notifications.
Here's everything this chapter covers, in the order you'll learn it:
- Real-time communication basics
- What a WebSocket is
- Establishing a socket connection
- Sending messages
- Receiving messages
- Connection events (open, close, error)
- Rooms / channels for grouping clients
- Authenticating socket connections
- Broadcasting to multiple clients
- Handling reconnection
- Building a simple chat application
- Live notifications
2Working Example
๐ป Example: WebSockets in Node.js
JavaScript
โถ Run in Compiler
import { WebSocketServer } from "ws";
const wss = new WebSocketServer({ port: 8080 });
wss.on("connection", (socket) => {
socket.on("message", (data) => {
console.log("Received:", data.toString());
socket.send("Message received!");
});
});
3Best Practices & Common Pitfalls
๐ก Key things to remember:
- Unlike HTTP's request-response model, a WebSocket connection stays open, letting the server push data to the client at any time โ essential for chat and live dashboards.
โ Frequently Asked Questions (FAQ)
Q What's the most important thing to understand about websockets in node.js?
Focus on: Real-Time Communication ยท Socket Connections ยท Sending/Receiving Messages ยท Rooms. These are the core building blocks this chapter's examples are built around, and they show up repeatedly in later chapters of this course.
Q Do I need external npm packages for websockets in node.js?
Only where explicitly shown in the code examples above (like Express, Zod, or Socket.IO) โ otherwise, this chapter relies entirely on Node.js's own built-in capabilities.