Phoenix JavaScript Client

1.8.5 · active · verified Sun Apr 19

The Phoenix JavaScript client provides real-time bidirectional communication capabilities for frontend applications interacting with Phoenix web framework backends. It leverages WebSockets and Phoenix Channels to enable features like chat, live notifications, and collaborative editing. The current stable version, 1.8.5, is released in conjunction with the Phoenix framework, leading to an irregular but consistent release cadence. A key differentiator is its robust channel-based publish/subscribe system, which is tightly integrated with the Elixir/Phoenix ecosystem, offering fault-tolerant and highly concurrent real-time services. It's designed to provide a structured approach to real-time communication, ensuring reliable message delivery and state management between client and server.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to establish a WebSocket connection to a Phoenix backend, join a specific channel, send messages to the channel, and handle incoming real-time events.

import { Socket } from "phoenix";

// Replace with your Phoenix server's WebSocket URL, e.g., 'ws://localhost:4000/socket'
const socketUrl = "ws://your-phoenix-app.com/socket";
const userToken = process.env.PHOENIX_AUTH_TOKEN ?? ''; // Use env var for auth or actual token

// Instantiate a new Socket connection
const socket = new Socket(socketUrl, { params: { userToken } });

// Connect to the socket
socket.connect();

socket.onOpen(() => console.log("Socket connected successfully!"));
socket.onError((error) => console.error("Socket error:", error));
socket.onClose(() => console.log("Socket closed."));

// Join a specific channel, e.g., 'room:lobby'
const channel = socket.channel("room:lobby", {});

// Set up event listeners for messages received on this channel
channel.on("new_msg", (payload) => {
  console.log("Received new message:", payload.body);
});

channel.on("user_joined", (payload) => {
  console.log("User joined channel:", payload.username);
});

// Attempt to join the channel and handle outcomes
channel.join()
  .receive("ok", ({ messages }) => {
    console.log("Joined channel successfully! Initial messages:", messages);
    // Push a message to the channel after successful join
    channel.push("new_msg", { body: "Hello Phoenix channel!" })
      .receive("ok", (msg) => console.log("Message pushed successfully:", msg))
      .receive("error", (reasons) => console.error("Failed to push message:", reasons))
      .receive("timeout", () => console.warn("Message push timed out."));
  })
  .receive("error", ({ reason }) => {
    console.error("Failed to join channel:", reason);
  })
  .receive("timeout", () => {
    console.warn("Joining channel timed out. Server might be unreachable or slow.");
  });

// Example of leaving a channel or disconnecting the socket after some time
// setTimeout(() => {
//   channel.leave();
//   socket.disconnect();
//   console.log("Channel left and socket disconnected after 15 seconds.");
// }, 15000);

view raw JSON →