vkashti / docs / next-websocket-fix.md
next-websocket-fix.md
Raw

Next.js WebSocket Fix

Issue

In Next.js 14.2.3, there's an issue with the WebSocket server used for Hot Module Replacement (HMR). You might see the following error when running the development server:

Error handling upgrade request TypeError: wsServer.handleUpgrade is not a function
    at HotReloaderWebpack.onHMR (/path/to/node_modules/next/dist/server/dev/hot-reloader-webpack.js:345:18)
    at upgradeHandler (/path/to/node_modules/next/dist/server/lib/router-server.js:451:59)
    at Server.<anonymous> (/path/to/node_modules/next/dist/server/lib/start-server.js:170:19)

What Causes This?

The error occurs because the WebSocket server (wsServer) is referenced directly in the HotReloaderWebpack's onHMR method, but it's not properly initialized.

How We Fixed It

We created a patch script at scripts/fix-nextjs-ws.js that modifies the Next.js hot-reloader-webpack.js file to properly initialize the WebSocket server.

The script is automatically run:

  1. After npm install through the postinstall hook in package.json
  2. Manually if needed by running node scripts/fix-nextjs-ws.js

Manual Fix (if needed)

If you encounter this error, you can run:

node scripts/fix-nextjs-ws.js

This will patch the Next.js file. After applying the patch, restart your development server.

Technical Details

The patch adds the following code to the onHMR method in hot-reloader-webpack.js:

// Create WebSocket server if not available
const WebSocketServer = require("ws").Server;
const wsServer = new WebSocketServer({ noServer: true });

This initializes the WebSocket server before it's used, which resolves the error.

Future Updates

When upgrading Next.js, you may need to re-apply this patch. The postinstall script should handle this automatically, but if you encounter WebSocket errors after an upgrade, run the fix script manually.