Skip to content

Commit

Permalink
fix: custom websocket server not upgrading due to next 13.4.3+
Browse files Browse the repository at this point in the history
It seems next v13.4.3 added a breaking change that causes sockets to be closed when not handled by HMR. As a result, websocket connections fail to upgrade. I've applied a fix from the following thread to address this issue for now:

vercel/next.js#50461 (comment)
  • Loading branch information
dougkulak authored Aug 30, 2023
1 parent 586362b commit 8ebde42
Showing 1 changed file with 10 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/server/prodServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const port = parseInt(process.env.PORT || '3000', 10);
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
const upgradeHandler = app.getUpgradeHandler();

void app.prepare().then(() => {
const server = http.createServer((req, res) => {
Expand All @@ -33,6 +34,15 @@ void app.prepare().then(() => {
console.log('SIGTERM');
handler.broadcastReconnectNotification();
});

server.on('upgrade', upgradeHandler);

// Keep the next.js upgrade handler from being added to our custom server
// so sockets stay open even when not HMR.
const originalOn = server.on.bind(server);
server.on = function (event, listener) {
return (event !== 'upgrade') originalOn(event, listener) : server;
};
server.listen(port);

console.log(
Expand Down

0 comments on commit 8ebde42

Please sign in to comment.