Skip to content

WebSocket upgrade fails with 200 OK response after successful beforeHandle #1169

Open
@patrik-u

Description

@patrik-u

What version of Elysia is running?

1.2.25

What platform is your computer?

Microsoft Windows NT 10.0.19045.0 x64

What steps can reproduce the bug?

  1. Start minimal ElysiaJS WS:
import Elysia from "elysia";

export const app = new Elysia()
    .ws("/ws", {
        // NO schemas (query, body) defined here
        beforeHandle({ request }) {
            const url = new URL(request.url);
            console.log(`Ultra-Minimal WS: beforeHandle. Path: ${url.pathname}`);
            // Just return a dummy context synchronously
            return { userId: "ultra-minimal-user" };
        },
        open(ws) {
            console.log(`Ultra-Minimal WS: Opened! Context: ${JSON.stringify(ws.data)}`);
            ws.send("Ultra-Minimal Connected!");
        },
        message(ws, message) {
            console.log(`Ultra-Minimal WS: Message: ${message}`);
            ws.send(`Echo: ${message}`);
        },
        close(ws, code, reason) {
            console.log(`Ultra-Minimal WS: Closed. Code: ${code}, Reason: ${reason}`);
        },
    })
    .get("/", () => "Hello")
    .listen(3000, () => {
        console.log("Ultra-Minimal Elysia server running on port 3000");
    });
  1. Run: wscat -c "ws://127.0.0.1:3000/ws"

  2. Observe Unexpected server response: 200.

  3. Run minimal_ws_test.ts.

// minimal_ws_test.ts
import { type WebSocketHandler } from "bun";

console.log("Starting minimal Bun WebSocket server...");

const server = Bun.serve({
    port: 3001, // Use a different port
    fetch(req, server) {
        const url = new URL(req.url);
        if (url.pathname === "/ws_minimal") {
            console.log("Minimal WS: Received upgrade request");
            // Simulate basic auth check - just check if token exists
            const token = url.searchParams.get("token");
            if (!token) {
                console.log("Minimal WS: No token, rejecting.");
                return new Response("Auth token required", { status: 401 });
            }

            console.log("Minimal WS: Token found, attempting upgrade...");
            const success = server.upgrade(req, {
                data: { authToken: token }, // Pass data like Elysia context
            });

            if (success) {
                console.log("Minimal WS: Upgrade call successful.");
                // Bun automatically handles sending the 101 response here
                return undefined;
            } else {
                console.log("Minimal WS: Upgrade call failed.");
                return new Response("Upgrade failed", { status: 500 });
            }
        }
        return new Response("Not Found", { status: 404 });
    },
    websocket: {
        open(ws) {
            console.log(`Minimal WS: Socket opened! Data: ${JSON.stringify(ws.data)}`);
        },
        message(ws, message) {
            console.log(`Minimal WS: Received message "${message}" from ${ws.data.authToken}`);
            ws.send(`Echo: ${message}`);
        },
        close(ws, code, reason) {
            console.log(`Minimal WS: Socket closed. Code: ${code}, Reason: ${reason}`);
        },
    } satisfies WebSocketHandler<{ authToken: string }>,
});

console.log(`Minimal Bun WebSocket server listening on port ${server.port}`);
  1. Run wscat -c ws://127.0.0.1:3001/ws_minimal?token=test.

  2. Observe successful connection.

What is the expected behavior?

Successful connection after running: wscat -c "ws://127.0.0.1:3000/ws"

What do you see instead?

I see Unexpected server response: 200.

Additional information

No response

Have you try removing the node_modules and bun.lockb and try again yet?

Yes.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions