Use phoenix.js in other project

Hello,

My question: Is it possible to use the phoenix.js file in other project.
Actualy i want build a websocket server with phoenix an connect it from an external nodeJS app.
But when i require(‘phoenix’)

I get this error:

Cannot read property ‘WebSocket’ of undefined
at new e (/Users/user1/node_modules/phoenix/priv/static/phoenix.js:1:10119)

1 Like

Hello welcome,

did You try to use the npm package? You can find it here
https://www.npmjs.com/package/phoenix

3 Likes

WebSocket is a browser API and isn’t available in Node.

hi, kokolegorille

Yes, I try to use this package.

I’m sure it’s possible.

I am using phoenix-channels to connect to our Phoenix app from Node.js.

Works fine so far

5 Likes

Thx jdj_dk

For test i have created a little node script

const { Socket } = require('phoenix-channels')
let socket = new Socket("ws://127.0.0.1:4000/socket")
let channel = socket.channel("interlocutors:fezfezfzef", {})
channel.join()
  .receive("ok", resp => { console.log("Joined successfully", resp) })
  .receive("error", resp => { console.log("Unable to join", resp) })

But when i run it nothing seems to be happening.
My elixir code work beacause when i send raw socket with https://github.com/esphen/wsta all is good.

defmodule ServerWeb.UserSocket do
  use Phoenix.Socket

  ## Channels
   channel "interlocutors:*", ServerWeb.InterlocutorsChannel
 
  # Socket params are passed from the client and can
  # be used to verify and authenticate a user. After
  # verification, you can put default assigns into
  # the socket that will be set for all channels, ie
  #
  #     {:ok, assign(socket, :user_id, verified_user_id)}
  #
  # To deny connection, return `:error`.
  #
  # See `Phoenix.Token` documentation for examples in
  # performing token verification on connect.
  def connect(_params, socket, _connect_info) do
    {:ok, socket}
  end

  # Socket id's are topics that allow you to identify all sockets for a given user:
  #
  #     def id(socket), do: "user_socket:#{socket.assigns.user_id}"
  #
  # Would allow you to broadcast a "disconnect" event and terminate
  # all active sockets and channels for a given user:
  #
  #     ServerWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{})
  #
  # Returning `nil` makes this socket anonymous.
  def id(_socket), do: nil
end

defmodule ServerWeb.InterlocutorsChannel do
  use ServerWeb, :channel

  def join("interlocutors:" <> int_id, _params, socket) do
    IO.puts(int_id)

    {:ok, socket}
  end

  def handle_in("new_message", _params, socket) do
    IO.puts("hello")

    {:noreply, socket}
  end

end

I don’t understand why it doesn’t work for me.

Oups sorry i forgot the socket.connect(). it’s work nice thx !!!

This package was really helpful. Thanks.

2 Likes