How to connect a NodeJS server to Phoenix via WebSockets?


I want to connect a NodeJS server to Phonix via WebSockets. However, the Phoenix client lib [1] does not work in Node - at least for me. It seems that this is a “browser” only library, right? Or is there a special trick to get it working in Node?

Thanks! :smiley:

[1] phoenix/assets/js at master · phoenixframework/phoenix · GitHub

1 Like

To my knowledge, Node.js doesn’t implement the WebSocket browser API, you will need a different library such as ws or uWebSockets, a polyfill or Deno.

It may also be easier to forgo the Phoenix “client library” and just create a standard WebSocket connection between the two, or just use plain HTTP requests.

1 Like

Try this:

const { Socket } = require("phoenix");
const ws = require("websocket").w3cwebsocket;
const socket = new Socket("http://localhost:4000/socket", {
    params: { token: "" },
    transport: ws

That works for me. It’s using the websocket - npm library.


Here is an example with ws npm package:

const ws = require("ws");
const { Socket } = require("phoenix");
const socket = new Socket("http://HOST/socket", { transport: ws });

You can create your own websocket abstraction, but I would recommend to go with phoenix built in package. It already does a lot of helpful stuff like keeping a connection alive.

1 Like