Connecting to a Rust websocket from a Next.JS frontend

I'm using Axum and trying to establish a websocket connection

pub async fn ws_handler(
    ws: WebSocketUpgrade,
) -> impl IntoResponse {
    ws.on_upgrade(move |socket| handle_socket(socket))
}

pub async fn handle_socket(mut socket: WebSocket) {
    while let Some(msg) = socket.recv().await {
        let msg = if let Ok(msg) = msg {
            msg
        } else {
            return;
        };

        if socket.send(msg).await.is_err() {
            return;
        }
    }
}

async fn main() {
    dotenv().ok();

    let http_host = env::var("HTTP_HOST").unwrap();

    let routes = routes::create_routes();

    let http_addr =
        SocketAddr::from_str(&http_host).unwrap();

    println!("Listening on http://{}", http_addr);

    axum::Server::bind(&http_addr)
        .serve(routes.into_make_service())
        .await
        .unwrap();
}

This is my code that is attached to a GET route. From my understanding I should hit this endpoint from my frontend in order for the connection to establish, but can't seem to get it working.

Is there a better way to create a websocket server in Axum? Perhaps a separate websocket server and a seperate http server

Why are you sending back the message that you just received?

Anyway, the code for your websocket route seems ok. Are you getting any error(s) when trying to establish a connection?

It seems to be ok, but this way of connecting to a websocket requires a GET request before the actual connection is made, it also says I need to send Connection: "upgrade" and Upgrade: "websocket" headers.

But upon researching I found out I can't actually modify the default Connection header.

Do you have any alternatives for building a websocket server for a chat application?

Thanks for the answer. :smiley:

What you're writing and what you are asking doesn't make sense to me. Sending the headers is the responsibility of the client, not of the server. If you want to setup the websocket connection from your React application, I recommend you to take a look at react-use-websocket.

As for how to setup the endpoint on the Axum server, I recommend you to take a look at the example provided on the Axum repository.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.