Using phoenix.js outside of a Phoenix application

Has anyone had success using the phoenix.js library for interacting with channels in a standalone node.js application?

For context, I am creating a web app from which I want to be able to control LEDs. The idea is that any browser with the web page pulled up is connected to a Phoenix channel, and there is a separate program running on a computer with LEDs attached also joined to that channel. When a message is broadcasted to that channel saying to change the lights, the client sees this and changes them accordingly.

My plan so far is to create a node application which controls LEDs and uses phoenix.js to communicate with channels. However, in testing this out, I installed phoenix.js 1.5.4 (npm install --save phoenix) and wrote the most basic code to create a Socket object

var phoenix = require('phoenix');
const { Socket } = phoenix;

var socket = new Socket('/socket', {params: null});

and I got the following error:

TyperError: Cannot read property 'WebSocket' of undefined
    at new e (/home/gpreston/code/webcandy2-client/node_modules/phoenix/priv/static/phoenix.js:1:10519)
    at Object.<anonymous> (/home/gpreston/code/webcandy2-client/app.js:4:14)

Is there something I’m missing? I know my environment setup is different than that of a mix phx.new project, but I’m having trouble figuring out what would cause such an error. I’m also not an expert on node, so apologies if this ends up looking kinda dumb…thanks for any help.

Using it should be no problem in a browser environment. In nodejs though you are missing some browser APIs like websocket.
You can try with polyfills but I don’t know which you’ll need exactly

Update for anyone wanting to do something similar: I ended up using this 3rd party Kotlin client library for Phoenix and it worked great. Seems like it’s advertised for Android but it works just the same in regular desktop Kotlin. Been meaning to try out Kotlin for something so this is the perfect thing to do that with :slight_smile:

1 Like