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)
The error occurs because the WebSocket server (wsServer
) is referenced directly in the HotReloaderWebpack's onHMR
method, but it's not properly initialized.
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:
npm install
through the postinstall hook in package.jsonnode scripts/fix-nextjs-ws.js
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.
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.
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.