How to create an Appsmith App which integrates with Websockets

Appsmith doesn’t support native integration with websockets or any form of RTC. An alternative people explore is to use the setInterval (JS) function to do polling of the API/Query they want to refresh.

How to integrate websockets with Appsmith?
To use websockets with Appsmith, we can take advantage of the IFrame widget provided. You can write HTML/JS code within the widget, which creates and handles the websocket connection.
You can create the connection using native javascript:
new WebSocket("wss://${websocket-endpoint}")
Websocket events like onopen, onmessage and onclose can be configured with the script tags.

How can we communicate between the Appsmith App and Iframe connected to websockets?
So the Iframe will be in charge of creating and managing the websocket connection.
Whenever response is received from the websockets in the onmessage function, you can postMessage it to the parent (ie the Appsmith App).
You can then access this data across the Appsmith instances and functions using Iframe1.message

Similarly you can add an event listener for message in the Iframe. This will allow Appsmith to send messages to the Iframe, and based on the message or data, it could do different functionalities as well.

Also, instead of writing HTML/JS inside the iframe, you can also host the page elsewhere like on your hosted domain or use third party code editors like Replit to host it. The deployed HTML url can then be used as the iframe src.

How to verify Websockets connection was successful?
You can verify that the websockets is connected and sending/receiving messages, from the WS section in the network tab.

App Link
Below is the link to an example Cryptocurrency App integrating websockets. You can fork and try it out yourself.
https://app.appsmith.com/app/websocket-poc-with-crypto/websocket-with-iframe-63da1136b8b46679d1911d98

Hope this helps. Do comment below how this hack helped and about any issues you faced and I can help further.

3 Likes