Assuming I want to run a custom next js server, and to accept websocket connections on that same server, how can I avoid clobbering the next js dev server hot reloading which is also using websockets on the same server...
const { createServer } = require('http')
const WebSocket = require("ws")
const { parse } = require('url')
const next = require('next')
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare().then(() => {
const server = createServer((req, res) => handle(req, res, parse(req.url, true)))
// pass the same server instance that is used by next js to the websocket server
const wss = new WebSocket.Server({ server })
wss.on("connection", async function connection(ws) {
console.log('incoming connection', ws);
ws.onclose = () => {
console.log('connection closed', wss.clients.size);
};
});
server.listen(port, (err) => {
if (err) throw err
console.log(`> Ready on http://localhost:${port} and ws://localhost:${port}`)
})
})
I believe this server should work in the production built version, so that the websocket server is created on the same server instance used to handle next js requests, but when I try to do this, the hot module reloading stops working, and errors appear in the chrome dev tools console because websocket connections it expects to be handled by webpack are now being handled by my custom websocket server.
How can I somehow route websocket connections for dev server to next and webpack and others to my own handler?
I know I can run my websocket server on another port, but I want to run it on the same server instance and same port as next js.