{"id":11551,"library":"phoenix","title":"Phoenix JavaScript Client","description":"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.","status":"active","version":"1.8.5","language":"javascript","source_language":"en","source_url":"git://github.com/phoenixframework/phoenix","tags":["javascript"],"install":[{"cmd":"npm install phoenix","lang":"bash","label":"npm"},{"cmd":"yarn add phoenix","lang":"bash","label":"yarn"},{"cmd":"pnpm add phoenix","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Socket is the primary entry point for establishing a connection to the Phoenix backend. It is a named export, commonly used in modern JavaScript/TypeScript environments.","wrong":"import Socket from 'phoenix';\nconst { Socket } = require('phoenix');","symbol":"Socket","correct":"import { Socket } from 'phoenix'"},{"note":"Channel instances are created via a connected Socket instance (`socket.channel(...)`), not directly imported. Do not attempt to import Channel as a top-level class.","wrong":"import { Channel } from 'phoenix';","symbol":"Channel","correct":"const channel = socket.channel('topic', params);"},{"note":"LongPoll is a named export available for fallback transport mechanisms when WebSockets are not available or preferred. It's less commonly used directly by applications unless specific fallback logic is required.","symbol":"LongPoll","correct":"import { LongPoll } from 'phoenix'"}],"quickstart":{"code":"import { Socket } from \"phoenix\";\n\n// Replace with your Phoenix server's WebSocket URL, e.g., 'ws://localhost:4000/socket'\nconst socketUrl = \"ws://your-phoenix-app.com/socket\";\nconst userToken = process.env.PHOENIX_AUTH_TOKEN ?? ''; // Use env var for auth or actual token\n\n// Instantiate a new Socket connection\nconst socket = new Socket(socketUrl, { params: { userToken } });\n\n// Connect to the socket\nsocket.connect();\n\nsocket.onOpen(() => console.log(\"Socket connected successfully!\"));\nsocket.onError((error) => console.error(\"Socket error:\", error));\nsocket.onClose(() => console.log(\"Socket closed.\"));\n\n// Join a specific channel, e.g., 'room:lobby'\nconst channel = socket.channel(\"room:lobby\", {});\n\n// Set up event listeners for messages received on this channel\nchannel.on(\"new_msg\", (payload) => {\n  console.log(\"Received new message:\", payload.body);\n});\n\nchannel.on(\"user_joined\", (payload) => {\n  console.log(\"User joined channel:\", payload.username);\n});\n\n// Attempt to join the channel and handle outcomes\nchannel.join()\n  .receive(\"ok\", ({ messages }) => {\n    console.log(\"Joined channel successfully! Initial messages:\", messages);\n    // Push a message to the channel after successful join\n    channel.push(\"new_msg\", { body: \"Hello Phoenix channel!\" })\n      .receive(\"ok\", (msg) => console.log(\"Message pushed successfully:\", msg))\n      .receive(\"error\", (reasons) => console.error(\"Failed to push message:\", reasons))\n      .receive(\"timeout\", () => console.warn(\"Message push timed out.\"));\n  })\n  .receive(\"error\", ({ reason }) => {\n    console.error(\"Failed to join channel:\", reason);\n  })\n  .receive(\"timeout\", () => {\n    console.warn(\"Joining channel timed out. Server might be unreachable or slow.\");\n  });\n\n// Example of leaving a channel or disconnecting the socket after some time\n// setTimeout(() => {\n//   channel.leave();\n//   socket.disconnect();\n//   console.log(\"Channel left and socket disconnected after 15 seconds.\");\n// }, 15000);\n","lang":"typescript","description":"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."},"warnings":[{"fix":"Consult the official Phoenix framework 1.1.x to 1.2.x upgrade guide (https://gist.github.com/chrismccord/29100e16d3990469c47f851e3142f766) and thoroughly test client functionality after the upgrade.","message":"Upgrading the Phoenix framework from v1.1.x to v1.2.x may require adjustments to the JavaScript client and careful review of the framework's upgrade instructions. While the changelog primarily lists backend changes, tight coupling often means client-side updates are necessary for compatibility or to leverage new features.","severity":"breaking","affected_versions":">=1.2.0"},{"fix":"Refer to the Phoenix framework 1.0.x to 1.1.0 upgrade instructions (https://gist.github.com/chrismccord/557ef22e2a03a7992624) and ensure the client library is updated to a compatible version.","message":"Upgrading the Phoenix framework from v1.0.x to v1.1.x might introduce incompatibilities with older JavaScript client versions. Although the client-specific API changes are not always detailed in the framework's changelog, major framework updates often necessitate updating the client library and reviewing integration points.","severity":"breaking","affected_versions":">=1.1.0"},{"fix":"Verify the `socketUrl` passed to the `Socket` constructor matches your Phoenix endpoint's WebSocket configuration. Check server logs for connection errors (e.g., firewall issues, incorrect port).","message":"The Phoenix client uses WebSockets for real-time communication. Ensure your WebSocket URL (e.g., `ws://localhost:4000/socket`) is correct, and that your Phoenix backend server is running and configured to accept WebSocket connections on that path and port.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure the channel topic string matches a configured topic on your Phoenix backend. Pass necessary authentication tokens in the `params` object when instantiating `Socket` or joining a `Channel`. Review server-side `UserSocket` and `Channel` authorization logic for any rejections.","message":"Channel join requests can be refused by the server due to incorrect topic names, missing or invalid authentication tokens, or server-side authorization policies. Always handle the `receive(\"error\")` callback from `channel.join()` to diagnose specific issues.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Start your Phoenix server, verify the `socketUrl` points to the correct address and port, and check firewall settings to ensure the port is open.","cause":"The Phoenix backend server is not running, the WebSocket URL is incorrect, or a firewall is blocking the connection to the specified port.","error":"WebSocket connection to 'ws://localhost:4000/socket' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED"},{"fix":"Examine the `reason` payload from the `receive(\"error\", ({ reason }) => ...)` callback for detailed error messages. Verify user authentication, the channel topic name, and review your Phoenix backend's `UserSocket` and `Channel` modules for authorization logic.","cause":"The server explicitly rejected the channel join request, commonly due to authentication failure, an invalid channel topic, or a server-side authorization policy preventing the join.","error":"channel join 'topic' was refused"},{"fix":"Check network connectivity between the client and the Phoenix server. Confirm the Phoenix server is running and not overloaded. The default join timeout can be adjusted in the `channel.join()` call if needed for slower networks.","cause":"The client did not receive an 'ok' or 'error' response from the server within the configured timeout period after attempting to join a channel. This might indicate network issues or an unresponsive server.","error":"channel join 'topic' timed out"}],"ecosystem":"npm"}