
Real-time communication is a game-changer for web applications, allowing users to interact with each other in a more dynamic and engaging way.
Express.js and WebSockets are a powerful combination for achieving real-time communication. This guide will walk you through the process of setting up a real-time communication system using Express.js and WebSockets.
Express.js is a popular Node.js framework that simplifies the process of building web applications. WebSockets, on the other hand, provide a bi-directional communication channel between a client and a server, enabling real-time data exchange.
With Express.js and WebSockets, you can create a real-time communication system that allows users to send and receive data instantly.
Suggestion: Websocket Node Js
What Is WebSockets?
A WebSocket is a communication protocol that allows an open connection to be maintained between the server and the client, enabling the server to send data to the client without a request.
This is in contrast to the traditional HTTP model, where the client always initiates the request.
For more insights, see: Client Websocket C#
Setting Up a Server

You need a server to run your WebSocket application, and it's often easier to run it alongside an existing Express server.
At scale, you may want to scale these independently, but for now, let's focus on setting up a simple server.
Express is a popular Node.js framework for building web applications, and it's a great choice for hosting your WebSocket server.
Here are the key things to keep in mind when setting up your server:
- The express-ws module can run on its own, but it's often easier to run it alongside an Express server.
- You can pass a custom http.Server to the server so that express-ws can use it for WebSocket upgrade handlers.
- Optionally, you can specify an object with options, such as leaveRouterUntouched or wsOptions.
These options allow you to customize the behavior of express-ws and fine-tune your server setup.
To set up express-ws, you'll need to call the express-ws function and pass in your Express app, server, and options.
Readers also liked: Websockets vs Sse

This will return a new object, referred to as wsInstance, which contains the underlying WebSocket server and other useful methods.
One of the key benefits of using express-ws is that it allows you to easily set up WebSocket connections and handle incoming messages.
By following these steps, you'll be well on your way to setting up a robust and scalable WebSocket server using Express.
Server Side Implementation
To create a WebSocket server using Express, you'll need to set up express-ws on your app. This involves modifying the global Router prototype for Express.
Express-ws can be set up on an existing Express application, which makes it easier to serve your app and WebSocket connections from the same server. At scale, you may want to scale these independently, but for now, it's a convenient option.
When setting up express-ws, you can pass an optional object with options to the server. This object can contain two properties: leaveRouterUntouched and wsOptions.
A different take: Websocket Scale
Here are the possible options you can include in this object:
- leaveRouterUntouched: set to true to prevent express-ws from modifying the Router prototype
- wsOptions: an object of options passed to the WebSocketServer constructor
The express-ws setup returns a new object, referred to as wsInstance in the documentation, which contains information about the WebSocket server.
Some key properties of the wsInstance object include:
- app: the Express app where express-ws was set up
- getWss(): returns the underlying WebSocket server/handler
- applyTo(router): sets up express-ws on a given router or other Router-like objects
You can use the wsInstance object to get a list of all connected WebSocket clients for this server, but note that this includes all clients, not just those for a specific route.
To create a WebSocket server, you'll need to add the WebSocket server implementation to your server.js file. This involves creating a WebSocket server attached to your HTTP server, which will handle real-time connections.
Here are the key events you can handle on the WebSocket server:
- connection: fires when clients connect, giving you access to individual WebSocket instances
- message: processes incoming text data
- close: manages disconnections
Handling Connections
Express exposes the upgrade event to get WebSocket connections by upgrading the HTTP connection to a WebSocket connection.
To handle WebSocket connections, you can use the ws npm module, which is the default library for WebSockets in Node.js. It's simple to integrate with Express and offers a straightforward API for building a WebSocket server and managing WebSocket events.
Explore further: Websocket Create Connection
Socket.io is another library that can aid in managing WebSockets in Express. It offers a simple API for handling connection, message, and disconnect events for a WebSocket server.
The connection, message, and disconnect events for a WebSocket server in Express are handled using socket.io. The server logs a message to the console whenever a user connects to it.
You can use the io.emit() method to deliver a message to all clients that are currently connected and log it to the console. The server reports a message to the console whenever a user disconnects from the server.
To manage WebSocket connection states, you can use the clientTracking option to enable automatic client management. This helps prevent memory leaks by detecting broken connections that haven't closed properly.
The readyState check ensures messages only go to open connections, and the ping/pong mechanism detects broken connections. You can also capture client IP addresses and provide detailed disconnection information.
The interval-based heartbeat system pings clients every 30 seconds to maintain connection health. This robust error handling is crucial for applications where connection stability matters.
To test the WebSocket connection, you can use tools like Postman or write a simple WebSocket client in JavaScript.
Take a look at this: Nextjs Socketio
Real-Time Features
Implementing real-time features is a crucial step in building interactive applications. You can use WebSockets for real-time communication in your application.
A chat application is a classic example of real-time communication. You can implement a basic chat feature using Express and WebSockets.
The server-side code for a real-time chat application is essential. It creates a simple chat interface where users can send messages that are broadcast to all connected clients in real-time.
Real-world WebSocket applications typically need to communicate with multiple clients simultaneously. You need a broadcasting capability to create interactive experiences like chat rooms or live updates.
Implementing a message broadcasting system shares messages among all connected clients. The ConnectionManager class maintains a Set of active WebSocket connections, providing clean methods for adding, removing, and broadcasting to clients.
When new clients connect, they receive a welcome message showing the current client count. Existing clients are notified of the new arrival. Messages from any client are broadcast to all others, creating a real-time chat experience.
You can test your real-time chat system by restarting your server and opening multiple browser tabs to http://localhost:3000. You'll see welcome messages, client count updates, and join notifications as new tabs connect.
For more insights, see: Websocket Client in Java
Managing Disconnections
Real-time applications must handle disconnections and automatically attempt to reconnect to ensure a seamless user experience.
This is especially important for applications that rely on websockets, where a lost connection can cause significant disruptions.
You can implement automatic reconnection on the client-side using JavaScript, which will attempt to reconnect to the server if the connection is lost.
For instance, with this code, the client will automatically attempt to reconnect to the server, minimizing downtime and keeping users engaged.
A different take: Websocket Reconnect
Testing
Testing a WebSocket connection can be done using tools like Postman or writing a simple WebSocket client in JavaScript.
To test the connection, you can use Postman or write a simple WebSocket client in JavaScript, just like the example shows.
Connecting to a server involves using a WebSocket client implementation, which is offered along with the server implementation.
Writing a simple WebSocket client in JavaScript is a great way to test the connection, as it allows you to see how the client interacts with the server.
The WebSocket client implementation is provided along with the server implementation, making it easy to get started with testing.
You can use Postman to test the WebSocket connection, or write a simple client in JavaScript to see how it works.
See what others are reading: Javascript Websocket
Authentication in

Authentication in WebSockets is crucial to protect our connections. A common way to implement authentication is to pass authentication tokens as parameters in the URL or in the headers during the connection establishment.
You can pass authentication tokens as parameters in the URL, which can be a convenient option for simple applications. However, this approach has security implications that need to be carefully considered.
Authentication tokens can also be passed in the headers, which provides a more secure way to authenticate WebSocket connections. This approach is more suitable for applications that require a higher level of security.
In both cases, the authentication token is typically a unique identifier that is generated by the server and sent to the client during the connection establishment process.
You might like: Websocket Headers
Best Practices and Scaling
As your application grows, you'll need to scale your WebSocket connections to handle a larger number of clients. Consider using solutions like Socket.IO, which builds on WebSockets and provides additional features like rooms, namespaces, and automatic reconnection.

To secure your WebSocket connections, use wss:// (WebSocket Secure) instead of ws:// and ensure all communications are encrypted. This is a crucial step to protect your data.
To keep your application running smoothly, close inactive connections that remain idle for a long time to avoid unnecessary resource consumption. This will help prevent your server from becoming overwhelmed.
Here are some best practices to keep in mind:
- Close inactive connections
- Limit message rate
- Handle errors correctly
- Use HTTPS and WSS
By implementing these best practices and scaling your WebSocket connections, you'll be able to handle a large number of clients and keep your application running efficiently.
Best Practices
When building a scalable application, it's essential to follow best practices to ensure smooth operation and prevent potential issues. Closing inactive connections can help avoid unnecessary resource consumption.
You'd be surprised how quickly inactive connections can add up and slow down your application. Closing them regularly can make a big difference.
To avoid overloading the server or client, it's crucial to implement a rate limit for messages sent through WebSockets. This ensures that your application can handle a large number of users without crashing.
Check this out: Webrtc Websocket Connections

Here are some key best practices to keep in mind:
- Close inactive connections to avoid unnecessary resource consumption.
- Limit message rate to avoid overloading the server or client.
- Handle errors correctly to prevent application crashes.
- Use HTTPS and WSS to secure WebSocket connections.
By following these best practices, you can ensure that your application runs smoothly and efficiently, even under heavy loads.
Scaling
Scaling is crucial as your application grows. Consider using solutions like Socket.IO, which builds on WebSockets and provides additional features.
Using Socket.IO can help you scale WebSocket connections to handle a larger number of clients. You can also scale your application horizontally by using a message broker like Redis to distribute messages across multiple WebSocket servers.
A message broker like Redis can help reduce the load on individual servers and improve overall performance. This allows you to add more servers as needed, ensuring your application can handle increased traffic.
By implementing these strategies, you can ensure your application remains scalable and can adapt to changing demands.
Related reading: Websocket vs Socket
Installing and Configuring
To get started with WebSockets in Express, you'll need to install the ws library. This is one of the most popular libraries for working with WebSockets in Node.js.

The ws library allows you to attach a WebSocket server to the existing HTTP server of Express, making it a great choice for this project.
The first step in setting up your project is to create a new folder and initialize a fresh Node.js project. You can do this by running the command `npm init -y` to set up a package.json file with default settings.
You'll also need to configure your project to use ES modules, which will allow you to use modern import/export syntax. This can be done by running the command `npm install --save-dev @babel/preset-env`.
To get started with Express, you'll need to create a main server file with the foundational Express configuration using ES modules. This will involve importing the necessary modules and creating an HTTP server.
The ws library makes it easy to configure a WebSocket server in your Express application.
Broaden your view: Python Websocket Library
Common Applications
Real-time updates are the name of the game when it comes to WebSockets. They're perfect for applications that need to stay fresh and up-to-date.

Chat applications, for instance, use WebSockets to enable real-time communication between users. This allows for seamless conversations without any lag or delay.
Multiplayer games can also benefit from WebSockets, synchronizing game state between players in real-time. This ensures that everyone is on the same page, so to speak.
Live notifications are another great use case for WebSockets. Applications can send real-time notifications to users, keeping them informed of status updates or messages.
Trading or stock applications can use WebSockets to send real-time price updates to users, helping them make informed decisions.
Here are some common applications that use WebSockets:
- Real-time chats
- Multiplayer games
- Live notifications
- Live price updates
Featured Images: pexels.com


