1 // NOTE: The contents of this file will only be executed if
2 // you uncomment its entry in "web/static/js/app.js".
4 // To use Phoenix channels, the first step is to import Socket
5 // and connect at the socket path in "lib/my_app/endpoint.ex":
6 import {Socket
} from "phoenix"
8 let socket
= new Socket("/socket", {params
: {token
: window
.userToken
}})
10 // When you connect, you'll often need to authenticate the client.
11 // For example, imagine you have an authentication plug, `MyAuth`,
12 // which authenticates the session and assigns a `:current_user`.
13 // If the current user exists you can assign the user's token in
14 // the connection for use in the layout.
16 // In your "web/router.ex":
18 // pipeline :browser do
21 // plug :put_user_token
24 // defp put_user_token(conn, _) do
25 // if current_user = conn.assigns[:current_user] do
26 // token = Phoenix.Token.sign(conn, "user socket", current_user.id)
27 // assign(conn, :user_token, token)
33 // Now you need to pass this token to JavaScript. You can do so
34 // inside a script tag in "web/templates/layout/app.html.eex":
36 // <script>window.userToken = "<%= assigns[:user_token] %>";</script>
38 // You will need to verify the user token in the "connect/2" function
39 // in "web/channels/user_socket.ex":
41 // def connect(%{"token" => token}, socket) do
42 // # max_age: 1209600 is equivalent to two weeks in seconds
43 // case Phoenix.Token.verify(socket, "user socket", token, max_age: 1209600) do
45 // {:ok, assign(socket, :user, user_id)}
46 // {:error, reason} ->
51 // Finally, pass the token on connect as below. Or remove it
52 // from connect if you don't care about authentication.
56 // Now that you are connected, you can join channels with a topic:
57 let channel
= socket
.channel("topic:subtopic", {})
59 .receive("ok", resp
=> { console
.log("Joined successfully", resp
) })
60 .receive("error", resp
=> { console
.log("Unable to join", resp
) })