What Is WebSockets? Build a Real-Time Chat Server with Express, NestJS, and MongoDB
You send a chat message and wait. Nothing happens. You refresh the page, and there it is, three messages late. ๐ That's what happens when a "live" feature is built on plain HTTP alone. The browser has to keep asking, "Anything new yet?" That's slow, wasteful, and a little embarrassing. So how do apps like chats, live dashboards, and multiplayer games update instantly? Most of them use WebSocketsโฆ
WebSockets provide a way for a browser and a server to maintain an open connection and communicate with each other at any time, similar to a phone call. Unlike regular HTTP, which sends letters back and forth like a traditional conversation, WebSockets allow both sides to speak whenever they like once the connection is established. This is achieved by initially using a normal HTTP request where the client asks the server to "upgrade" the connection, and if the server agrees, the connection becomes a WebSocket.
To build a real-time chat server using Express, NestJS, and MongoDB, you will use the Socket.IO library, which is built on top of WebSockets and adds features like rooms, automatic reconnection, and event names. However, it is important to note that Socket.IO is not a plain WebSocket server; it uses its own protocol on top, so a Socket.IO server needs a Socket.IO client. Using raw new WebSocket(...) in the browser won't work with Socket.IO.
Real-time features are widely used in applications today, such as chat and support widgets, live notifications, collaborative tools, and dashboards that update automatically. By using WebSockets, the server can push data the moment something happens, eliminating the need for the client to keep asking for updates. This results in less repeated requests and a smoother user experience. Additionally, understanding events and connections is a valuable skill that can be applied to build many kinds of live features.
Key benefits of WebSockets include instant updates, two-way communication, less repeated asking, rooms and targeted messages, and reconnection assistance. When compared to HTTP polling, WebSockets offer a more efficient way to handle frequent updates, as the client keeps a single open connection and waits for events instead of making multiple GET requests every few seconds.
Rooms and targeted messages allow sending messages only to specific groups, while reconnection help ensures that the connection can be automatically reestablished if interrupted.
Rewritten by urgent.news; may contain errors โ check the original.
Source: dev.to