The WebSockets module is platform-agnostic, hence, you can bring your own library (or even a native implementation) by making use of
WebSocketAdapter interface. This interface forces to implement few methods described in the following table:
|Creates a socket instance based on passed arguments|
|Binds the client connection event|
|Binds the client disconnection event (optional*)|
|Binds the incoming message to the corresponding message handler|
|Terminates a server instance|
The socket.io package is wrapped in an
IoAdapter class. What if you would like to enhance the basic functionality of the adapter? For instance, your technical requirements require a capability to broadcast events across multiple load-balanced instances of your web service. For this, you can extend
IoAdapter and override a single method which responsibility is to instantiate new socket.io servers. But first of all, let's install the required package.
Once the package is installed, we can create a
Afterward, simply switch to your newly created Redis adapter.
Another available adapter is a
WsAdapter which in turn acts like a proxy between the framework and integrate blazing fast and thoroughly tested ws library. This adapter is fully compatible with native browser WebSockets and is far faster than socket.io package. Unluckily, it has significantly fewer functionalities available out-of-the-box. In some cases, you may just don't necessarily need them though.
In order to use
ws, we firstly have to install the required package:
Once the package is installed, we can switch an adapter:
info Hint The
WsAdapteris imported from
Advanced (custom adapter)
For demonstration purposes, we are going to integrate the ws library manually. As mentioned, the adapter for this library is already created and is exposed from the
@nestjs/platform-ws package as a
WsAdapter class. Here is how the simplified implementation could potentially look like:
info Hint When you want to take advantage of ws library, use built-in
WsAdapterinstead of creating your own one.
Then, we can set up a custom adapter using
A working example that uses
WsAdapter is available here.