SolidJSS
SolidJS11mo ago
29 replies
Zikado

SolidStart Websocket Proxy

Hello,

I've tried to create a proxy to standalone websocket server in SolidStart, for purpose of this showcase I created a simple demo showing the issue I ran into.

index.js aka the websocket server
const WebSocket = require("ws");

const PORT = 8080;
const wss = new WebSocket.Server({ port: PORT });

wss.on("connection", (ws) => {
  console.log("New client connected");

  ws.send("Hello");

  ws.on("message", (message) => {
    console.log(`Received: ${message}`);
  });

  ws.on("close", () => {
    console.log("Client disconnected");
  });
});


then I have this very simple Websocket connection on the client

app.tsx
import { isServer } from "solid-js/web";

export default function App() {
  if (!isServer) {
    const connection = new WebSocket("ws://localhost:3000/ws");
    connection.onopen = () => {
      console.log("OPENED");
    };
    connection.onmessage = (e) => {
      console.log(JSON.stringify(e.data));
    };
  }
  return <main>Some content</main>;
}


and here is the proxy

app.config.ts
import { defineConfig } from "@solidjs/start/config";

export default defineConfig({
  vite: {
    server: {
      proxy: {
        "/ws": {
          target: "ws://localhost:8080",
          rewrite: (path) => path.replace(/^\/ws/, ""),
          ws: true,
          rewriteWsOrigin: true,
        },
      },
    },
  },
});


Now, the problem is that when trying to establish the ws connection it gets through to the server but gets closed immediately, so the console logs on the server would look like this
New client connected
Client disconnected

on the client it will take some time before eventually getting an error that the connection could not have been established.

I have also tried to recreate the same situation with SvelteKit but there it worked without any problem with the same setup (just edited vite.config directly).

I appreciate your help, thanks.
Was this page helpful?