# Add WebSockets to a Leptos App

Yes. An agent adds a WebSocket route to your Leptos and Axum app, a component that connects from the browser, a Playwright round-trip check, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-websockets/leptos/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads how the server and the client are split before adding a connection between them. In a project generated from leptos-rs/start-axum, `Cargo.toml` depends on `leptos`, `leptos_router` and `leptos_meta` 0.8 with `axum` 0.8, `leptos_axum` and `tokio` behind the `ssr` feature and `wasm-bindgen` with `console_error_panic_hook` behind `hydrate`; the `[package.metadata.leptos]` block names `style/main.scss`, `public` as the assets directory, `127.0.0.1:3000` as the address and `end2end` as the Playwright directory, and `rust-toolchain.toml` pins nightly. `src/main.rs` is compiled only with `ssr`: it builds an `axum::Router` with `leptos_routes` for the generated route list, `fallback(leptos_axum::file_and_error_handler(shell))` and `with_state(leptos_options)`, then serves on a `TcpListener`. `src/app.rs` holds `shell`, `App` with a `Router` and one `Route` for `HomePage`, and `HomePage` itself, a counter button on an `RwSignal`. `src/lib.rs` exports `app` and the `hydrate` entry. `end2end/tests/example.spec.ts` opens `/` and checks the title and heading. The template is a cargo-generate template, so `{{project-name}}` and `{{crate_name}}` appear in `Cargo.toml`, `main.rs` and `app.rs` until `cargo leptos new` fills them in; the agent works on the generated project.

The server side is an Axum route, because a Leptos server function is a request and a response and cannot hold a socket open. The agent enables the `ws` feature on `axum` and adds `futures` under the `ssr` feature, then adds `src/ws.rs`, compiled only with `ssr`, with a handler taking `WebSocketUpgrade` and returning `ws.on_upgrade(handle_socket)`; `handle_socket` splits the `WebSocket` with `StreamExt::split`, echoes each `Message::Text` back prefixed with the server's receive time, answers `Ping` frames, and returns when `recv()` yields `None` or a `Close`, logging through `leptos::logging::log` as `main.rs` does. In `main.rs` the route goes in as `.route("/ws", axum::routing::get(ws::ws_handler))` before `leptos_routes`, so Leptos's fallback never sees the path, and shares the existing `with_state`. Text frames are `Utf8Bytes`, so the handler converts to `String` once at the edge.

The client side uses the `leptos-use-websocket` crate from the leptos-use family, which publishes one small crate per function and whose 0.20 line targets Leptos 0.8, with `codee` for the codec. A `LiveFeed` component in `app.rs` calls `use_websocket::<String, String, FromToStringCodec>("/ws")`; the hook resolves the relative path against the page's location and picks `ws` or `wss` to match `http` or `https`, so one string works in `cargo leptos watch` and behind a TLS proxy. The component renders `ready_state`, keeps the last received `message` in a signal, and sends the text of an input through `send`; `reconnect_limit` stays at the default of three attempts. The crate's `ssr` feature is added to the project's `ssr` feature list, because on the server the hook's functions are no-ops and the component must still render the connecting state into the HTML, with the socket opened only after hydration. `HomePage` gets `<LiveFeed/>` under the counter.

The check is the project's own end-to-end setup. `end2end/tests/websocket.spec.ts` opens `/`, waits for the status text to read `Open`, types a message, clicks send and expects the echoed text to appear, and `example.spec.ts` keeps its title and heading assertions. The agent runs `cargo leptos build`, then `cargo leptos end-to-end`, which starts the server on `127.0.0.1:3000` and runs Playwright from `end2end`, after `npm install` there and the browser download. It also runs `cargo clippy --features ssr` and `--features hydrate` separately, since the two feature sets compile different code, and quotes both.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add a WebSocket connection to this Leptos and Axum app. Read Cargo.toml including the package.metadata.leptos block, rust-toolchain.toml, src/main.rs, src/app.rs, src/lib.rs, end2end/package.json and end2end/tests first. On the server, enable axum's ws feature and add futures under the ssr feature, add a ws module compiled only with ssr whose handler upgrades with WebSocketUpgrade, splits the socket, echoes each text frame back with a timestamp, answers pings and exits on close, and mount it at /ws before leptos_routes in main.rs. On the client, add the leptos-use-websocket crate at the line matching Leptos 0.8 with codee, enable its ssr feature under the project's ssr feature, and add a LiveFeed component using use_websocket with FromToStringCodec on the relative path /ws that shows the ready state, the last message and an input that sends; render it on the home page. Add a Playwright test under end2end that waits for the open state, sends a message and expects the echo. Run cargo clippy for the ssr and hydrate feature sets, cargo leptos build and cargo leptos end-to-end, and open a pull request quoting the results.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

The pull request adds `src/ws.rs` and `end2end/tests/websocket.spec.ts` and changes `Cargo.toml`, `Cargo.lock`, `src/main.rs`, `src/app.rs` and `end2end/package-lock.json` if the Playwright version moved. Its description quotes the two `clippy` runs, the `cargo leptos build` output with the WASM size the build prints, and the Playwright report with both spec files passing, and shows the browser's network view is not needed because the test asserts on the echoed text.

A reviewer checks what the handler does with a frame, since the echo is a placeholder for their own messages, decides whether the route needs the same authentication as the rest of the app, and reads the `ssr` and `hydrate` feature lists, where the one real mistake is a crate pulled into the WASM build by accident. Running `cargo leptos watch` and opening the page shows the status move to open.

The route list, the `shell`, the stylesheet and the fallback handler are unchanged, and the counter on the home page still works without the socket.

## Run it on every Linear issue labelled websocket

In the console, add an automation to the Project with this prompt and a `linear` trigger on `linear.issue.labeled`, filtered to the `websocket` label. When someone labels an issue such as "the dashboard should update without reloading", the trigger puts the issue after the prompt and the run reads which page and which messages it describes before writing the handler. Only label changes by a person in your Rush org fire it, and the automation starts at most `max_runs_per_hour` runs in an hour.

An automation's runs are read-only, so the run that pushes the branch is started from your own server: a handler receiving the automation's comment sends this body to `POST /o/{org}/sessions` with the issue URL in `resources` and a `request_id` that is a UUID v5 of the issue id, so a redelivered event returns the run already started.

## Why run it on Rush?

A Leptos app compiles twice, once for the server and once for WebAssembly, and a WebSocket touches both: an Axum feature and a handler on one side, a hook and a codec on the other, and feature lists that decide which crate lands in which build. The agent reads the feature lists as they are, adds each dependency under the feature that needs it, and runs clippy per feature set and the project's own Playwright suite in its sandbox, with the commands and their output kept in the run's record.

The relative URL and the capability of the hook to be a no-op on the server are the two details that make the same component work in development, in a TLS deployment and in server-rendered HTML, and the pull request explains both so the next socket in the app follows the same shape.

## Frequently asked questions

### Why not a server function?

A `#[server]` function is one request and one response over HTTP, which Leptos encodes and decodes for you. A WebSocket stays open and carries frames both ways, so it needs an Axum route with `WebSocketUpgrade`, mounted on the same `Router` before `leptos_routes` so the Leptos fallback never answers `/ws`.

### Does the component work with server-side rendering?

Yes. With the crate's `ssr` feature on under the project's `ssr` feature, the hook's `open`, `send` and `close` are no-ops on the server, so the component renders its connecting state into the HTML, and the browser opens the socket after hydration. Without that feature the server build would not compile.

### Why a relative /ws path?

The hook resolves a path against the page's location and uses `ws` for an `http` page and `wss` for an `https` one. One string therefore works at `127.0.0.1:3000` under `cargo leptos watch` and behind a TLS terminator in production, without an environment variable for the socket host.

### What happens when the connection drops?

The hook reconnects up to `reconnect_limit` times, three by default, and the counter resets each time a connection opens; the component shows the state while it retries. Setting `ReconnectLimit::Infinite` in the options keeps trying forever, and the pull request shows that line.

### Can the server push without a client message?

Yes. The handler holds the sender half after `split`, so a `tokio` task can send frames on a timer or from a broadcast channel while the receiver half waits for client frames. The echo with a timestamp is the smallest handler that proves both directions; the pull request marks where a broadcast would go.

## More Leptos jobs

- [Add Response Compression to a Leptos Axum App](https://getrush.ai/run/add-compression/leptos/)
- [Add a Dark Mode Toggle to a Leptos App](https://getrush.ai/run/add-dark-mode/leptos/)
- [Add a Dockerfile to a Leptos Axum App](https://getrush.ai/run/add-dockerfile/leptos/)

## The same job on other stacks

- [Add WebSockets to a Litestar App](https://getrush.ai/run/add-websockets/litestar/)
- [Add a WebSocket Endpoint to a Vapor App from a Linear Issue](https://getrush.ai/run/add-websockets/vapor/)
- [Add WebSockets to an aiohttp App](https://getrush.ai/run/add-websockets/aiohttp/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
