WebSockets: Uncaught (in response) Error: The script will never generate a response.

I have a very simple function that listens for WebSocket connections and sends the current time whenever a message is received:
export const onRequest: PagesFunction = context => {
const upgradeHeader = context.request.headers.get("Upgrade")
if (upgradeHeader !== "websocket") {
return new Response("Expected websocket", { status: 400 })
}

const [client, server] = Object.values(new WebSocketPair());

server.accept();
server.addEventListener("message", () => {
server.send((Date.now()).toString());
});

return new Response(null, {
status: 101,
webSocket: client
});
}
export const onRequest: PagesFunction = context => {
const upgradeHeader = context.request.headers.get("Upgrade")
if (upgradeHeader !== "websocket") {
return new Response("Expected websocket", { status: 400 })
}

const [client, server] = Object.values(new WebSocketPair());

server.accept();
server.addEventListener("message", () => {
server.send((Date.now()).toString());
});

return new Response(null, {
status: 101,
webSocket: client
});
}
The script is working fine but every time the WebSocket is closed by the client, the following error is logged:
✘ [ERROR] Uncaught (in response) Error: The script will never generate a response.
✘ [ERROR] Uncaught (in response) Error: The script will never generate a response.
The only information I've seen about this error has to do with either Promises or external libraries, neither of which I am using so I am confused as to what is causing this error message.
1 Reply
LeftyLlama
LeftyLlamaOP6d ago
I figured it out, the issue is that there that the WebSocket is never properly closed, meaning that the function reaches a state where it can never be resolved. Adding a listener like this fixes it:
server.addEventListener("close", () => {
server.close();
});
server.addEventListener("close", () => {
server.close();
});
Want results from more Discord servers?
Add your server