# Websocket connections inside a function node

**URL:** <https://discourse.nodered.org/t/websocket-connections-inside-a-function-node/87436>\
**Category:** General\
**Tags:** websocket\
**Created:** [23 April 2024 12:57 UTC](https://discourse.nodered.org/t/websocket-connections-inside-a-function-node/87436 "2024-04-23T12:57:35Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![kitori](https://avatars.discourse-cdn.com/v4/letter/k/f08c70/32.png) [@kitori](https://discourse.nodered.org/u/kitori)\
**Post date:** [23 April 2024 12:57 UTC](https://discourse.nodered.org/t/websocket-connections-inside-a-function-node/87436/1 "2024-04-23T12:57:35Z")

</div>

Is it possible to use a Websocket connection inside a function node?  
Native Websocket dont work:  
[WebSocket - Web APIs | MDN](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket?retiredLocale=de) ,

This as well:

> **[GitHub - websockets/ws: Simple to use, blazing fast and thoroughly tested...](https://github.com/websockets/ws?tab=readme-ov-file#sending-and-receiving-text-data)**
>
> Simple to use, blazing fast and thoroughly tested WebSocket client and server for Node.js - websockets/ws

🌋 🌋 🌋_ **! function node "ws" will crash node red** _ 🌋 🌋 🌋

```auto
[{"id":"1806fbe5e8308245","type":"function","z":"527fe7341bb5fe46","name":"WebSocket","func":"// Create WebSocket connection.\nconst socket = new WebSocket(\"ws://localhost:8080\");\n\n// Listen for messages\nsocket.addEventListener(\"message\", (event) => {\n node.send(\"Message from server \", event.data);\n});\n","outputs":1,"timeout":0,"noerr":2,"initialize":"","finalize":"","libs":[],"x":930,"y":940,"wires":[["a3401fa602e2acc3"]]},{"id":"a3401fa602e2acc3","type":"debug","z":"527fe7341bb5fe46","name":"debug 16","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","statusVal":"","statusType":"auto","x":1100,"y":940,"wires":[]},{"id":"751f8cd47462a495","type":"function","z":"527fe7341bb5fe46","name":"ws","func":"// Create WebSocket connection.\nconst socket = new WebSocket(\"ws://localhost:8080\");\n\n// Listen for messages\nsocket.addEventListener(\"message\", (event) => {\n node.send(\"Message from server \", event.data);\n});\n","outputs":1,"timeout":0,"noerr":0,"initialize":"","finalize":"","libs":[{"var":"WebSocket","module":"ws"}],"x":950,"y":980,"wires":[["a3401fa602e2acc3"]]},{"id":"4b7297e5521cfb6f","type":"inject","z":"527fe7341bb5fe46","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":800,"y":980,"wires":[["751f8cd47462a495"]]}]

```

Similar question, same problem 😃

> [@Using Dynamic URL websocket node](https://discourse.nodered.org/t/using-dynamic-url-websocket-node/85384):
>
> I would like to use a websocket interface in node-red. For this I need a dynamic url, because I need a token for access. This changes every 24 hours. Are there approaches to use a dynamic url for the websocket node?

---

<div class="post-metadata">

**Author:** ![TotallyInformation](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/totallyinformation/32/31_2.png) [@TotallyInformation](https://discourse.nodered.org/u/TotallyInformation)\
**Post date:** [23 April 2024 19:12 UTC](https://discourse.nodered.org/t/websocket-connections-inside-a-function-node/87436/2 "2024-04-23T19:12:07Z")

</div>

Do you need a raw websocket? Is the page you are connecting to served by Node-RED or somewhere else?

UIBUILDER has built in comms between Node-RED and the web page, no code required. It uses [Socket.IO](http://Socket.IO) rather than just raw websockets though. SIO uses websockets from within its own library but can also fall back to other connections like long-polling if ws isn't reliable or is blocked.

It is easiest to use when serving the page using a uibuilder node but it IS also possible to serve pages from an external web server if you really have to.

If you genuinely require raw websockets, you can use the appropriate websocket node, no need to get complex in a function node.

---

<div class="post-metadata">

**Author:** ![kitori](https://avatars.discourse-cdn.com/v4/letter/k/f08c70/32.png) [@kitori](https://discourse.nodered.org/u/kitori)\
**Post date:** [24 April 2024 05:24 UTC](https://discourse.nodered.org/t/websocket-connections-inside-a-function-node/87436/3 "2024-04-24T05:24:40Z")

</div>

i try to understand how the loxone miniserver communication works. And im prototyping a lot with node-RED, so...

> **[CommunicatingWithMiniserver.pdf](https://www.loxone.com/wp-content/uploads/datasheets/CommunicatingWithMiniserver.pdf)**
>
> 661.08 KB

another use-case is a dynamik subsciption to some ntfy.sh topics for getting notification forwarded:

> **[Using the API - ntfy](https://docs.ntfy.sh/subscribe/api/#websockets)**
>
> Send push notifications to your phone via PUT/POST

---

<div class="post-metadata">

**Author:** ![TotallyInformation](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/totallyinformation/32/31_2.png) [@TotallyInformation](https://discourse.nodered.org/u/TotallyInformation)\
**Post date:** [24 April 2024 08:09 UTC](https://discourse.nodered.org/t/websocket-connections-inside-a-function-node/87436/4 "2024-04-24T08:09:45Z")

</div>

Try using a websocket-in node set to "Connect to".

---

<div class="post-metadata">

**Author:** ![kitori](https://avatars.discourse-cdn.com/v4/letter/k/f08c70/32.png) [@kitori](https://discourse.nodered.org/u/kitori)\
**Post date:** [24 April 2024 08:37 UTC](https://discourse.nodered.org/t/websocket-connections-inside-a-function-node/87436/5 "2024-04-24T08:37:37Z")

</div>

This work as expected:  
Example flow with the current Websocket node:

```auto
[{"id":"2fa00c98ec58c282","type":"subflow","name":"ntfy publish","info":"","category":"","in":[{"x":60,"y":80,"wires":[{"id":"f5615ba774f12910"}]}],"out":[{"x":800,"y":80,"wires":[{"id":"93bf5eeaec8ee2c9","port":0}]}],"env":[{"name":"server","type":"str","value":"https://ntfy.sh"},{"name":"topic","type":"str","value":""},{"name":"title","type":"str","value":""},{"name":"priority","type":"str","value":"3","ui":{"type":"select","opts":{"opts":[{"l":{"de":"Max priority"},"v":"5"},{"l":{"de":"High priority"},"v":"4"},{"l":{"de":"Default priority"},"v":"3"},{"l":{"de":"Low priority"},"v":"2"},{"l":{"de":"Min priority"},"v":"1"}]}}},{"name":"tags","type":"str","value":""}],"meta":{},"color":"#5eead4","icon":"font-awesome/fa-file-code-o","status":{"x":800,"y":140,"wires":[{"id":"c48d9f5358654b76","port":0}]}},{"id":"93bf5eeaec8ee2c9","type":"http request","z":"2fa00c98ec58c282","name":"","method":"POST","ret":"obj","paytoqs":"ignore","url":"","tls":"","persist":false,"proxy":"","insecureHTTPParser":false,"authType":"","senderr":false,"headers":[],"x":450,"y":80,"wires":[["c48d9f5358654b76"]]},{"id":"f5615ba774f12910","type":"function","z":"2fa00c98ec58c282","name":"headers + url","func":"let server = msg.server || env.get(\"server\");\nlet topic = msg.topic || env.get(\"topic\");\nlet title = msg.title || env.get(\"title\");\nlet priority = msg.priority || env.get(\"priority\") || 3\nlet tags = msg.tags || env.get(\"tags\") || ''\n\nlet headers = {\n 'Title': title,\n 'Priority': priority,\n 'Tags': tags\n}\n\n\nmsg.headers = headers\n\n\nmsg.url = server + \"/\" + topic\n\nreturn msg;\n\n\n\n\nreturn msg;","outputs":1,"timeout":0,"noerr":0,"initialize":"","finalize":"","libs":[],"x":240,"y":80,"wires":[["93bf5eeaec8ee2c9"]]},{"id":"c48d9f5358654b76","type":"change","z":"2fa00c98ec58c282","name":"statusCode","rules":[{"t":"set","p":"payload","pt":"msg","to":"statusCode","tot":"msg"}],"action":"","property":"","from":"","to":"","reg":false,"x":630,"y":140,"wires":[[]]},{"id":"ecdb97541723a1e3","type":"inject","z":"527fe7341bb5fe46","name":"","props":[{"p":"payload"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"\"Test notification from node-red at \" & $now()\t","payloadType":"jsonata","x":170,"y":280,"wires":[["e07909ce6f1faea4"]]},{"id":"035b96386fe1697e","type":"debug","z":"527fe7341bb5fe46","name":"debug 12","active":false,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","statusVal":"","statusType":"auto","x":580,"y":280,"wires":[]},{"id":"e07909ce6f1faea4","type":"subflow:2fa00c98ec58c282","z":"527fe7341bb5fe46","name":"ntfy publish","env":[{"name":"topic","value":"Change-Me","type":"str"},{"name":"title","value":"test","type":"str"},{"name":"priority","value":"5","type":"str"},{"name":"tags","value":"+1","type":"str"},{"name":"Title","value":"Test","type":"str"},{"name":"Priority","value":"5","type":"str"}],"x":370,"y":280,"wires":[["035b96386fe1697e"]]},{"id":"6858cd8fd8908d02","type":"websocket in","z":"527fe7341bb5fe46","name":"ntfy","server":"","client":"879565134ff524f5","x":150,"y":360,"wires":[["17e6d8b516ce1040"]]},{"id":"4e06a51da8bc0dc0","type":"debug","z":"527fe7341bb5fe46","name":"debug 19","active":true,"tosidebar":true,"console":false,"tostatus":true,"complete":"true","targetType":"full","statusVal":"payload.message","statusType":"msg","x":460,"y":360,"wires":[]},{"id":"17e6d8b516ce1040","type":"json","z":"527fe7341bb5fe46","name":"","property":"payload","action":"","pretty":false,"x":310,"y":360,"wires":[["4e06a51da8bc0dc0"]]},{"id":"879565134ff524f5","type":"websocket-client","path":"wss://ntfy.sh/Change_me/ws","tls":"","wholemsg":"false","hb":"0","subprotocol":""}]

```

But when i have a list of topics which i want to subscribe, i have to fiddle it manually into the Websocket node, because it has a configuration node.

So i need a node which inputs a url and then connect a Websocket to it.

---

<div class="post-metadata">

**Author:** ![crisconru](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/crisconru/32/38995_2.png) [@crisconru](https://discourse.nodered.org/u/crisconru)\
**Post date:** [24 April 2024 10:14 UTC](https://discourse.nodered.org/t/websocket-connections-inside-a-function-node/87436/6 "2024-04-24T10:14:40Z")

</div>

You cannot use standard Websockets inside Node-Red because it is base on NodeJS. You need to use an external library like [ws](https://github.com/websockets/ws)

Evenmore, inside a function Node it is not the best for that. Use the built-in components.

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/1X/d073cd938eafa2e558d7c2cd59003b3ef4963033.png) [@system](https://discourse.nodered.org/u/system)\
**Post date:** [8 May 2024 10:15 UTC](https://discourse.nodered.org/t/websocket-connections-inside-a-function-node/87436/7 "2024-05-08T10:15:28Z")

</div>

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.
