Next.js Discord

Discord Forum

Next.js API route to upgrade request into web socket (ws package)

Unanswered
Northeast Congo Lion posted this in #help-forum
Open in Discord
Northeast Congo LionOP
Hey people! I'm currently using a custom server for Next.js (Koa). With Koa, I have added a route, /api/web-socket to upgrade the request into a web socket, via the ws packge (utilizing the provided handleUpgrade function). This works well. However, my end goal is to get rid of Koa and only utilize Next.js' API routes. Therefore, I've replaced my Koa route with a Next.js API route. The file is called pages/api/web-socket.ts and it does the exact same thing. Here is the code:
import type {NextApiHandler} from "next";
import {handleUpgrade} from "~/server/library/web-socket";

const handler: NextApiHandler = async (request, response) => {
    const upgrade = request.headers.upgrade;
    const connection = request.headers.connection;

    if (upgrade?.toLowerCase() !== "websocket" || connection?.toLowerCase() !== "upgrade") {
        response.status(400).end();
        return;
    }

    handleUpgrade(request);
};

export default handler;


My own handleUpgrade function simply delegates to the ws one:
export const handleUpgrade = (request: IncomingMessage) => {
    const server = global.webSocket.server;
    server.handleUpgrade(
        request,
        request.socket,
        Buffer.alloc(0),
        ws => {
            server.emit("connection", ws, request);
        },
    );
};


When I do this, I get invalid frame header. This works perfectly fine with Koa, with basically the same code. Anyone have any idea why? Is there some limitation in the Next.js API routes that prevents me to do this?

I use Next.js 13.2.4 and ws 8.13.0.

4 Replies

Northeast Congo LionOP
I forgot to mention. To get this to work with Koa, I must also tell it to bypass Koa's built in response handling, via context.respond = false. Without this, I get invalid frame header with Koa too. Maybe that's the problem with Next.js? Is there a similar option for Next.js? I kind of figured that not setting anything on the response would be sufficielt. 😬 But apparantly not.
Northeast Congo LionOP
FYI: I'll also try my luck on the Github discussions:
https://github.com/vercel/next.js/discussions/53780
@Northeast Congo Lion if u still have this issue, can u try running the app via bun or deno?
I had the same issue aswell, after i run my api with bun the issue went away