pjnicolas
pjnicolas17mo ago

"Fast Refresh" messing with my WebSocketServer in Next.js development

I got my websockets up and running in tRPC + Next.js with this code:
import { WebSocketServer } from 'ws'
import { applyWSSHandler } from '@trpc/server/adapters/ws'

// [...]

const wss = new WebSocketServer({
port: 3001,
})

const handler = applyWSSHandler({
wss,
router: appRouter,
createContext,
})
import { WebSocketServer } from 'ws'
import { applyWSSHandler } from '@trpc/server/adapters/ws'

// [...]

const wss = new WebSocketServer({
port: 3001,
})

const handler = applyWSSHandler({
wss,
router: appRouter,
createContext,
})
...and it's working like a charm. But when I change something in any server file and reload my webapp, I get this error in my server console:
WebSocket Server error Error: listen EADDRINUSE: address already in use :::3001
[...]
WebSocket Server error Error: listen EADDRINUSE: address already in use :::3001
[...]
So I guess Next.js is re-running the files and trying to re-create the server. Is there any way I can prevent Next.js of doing that? Or is there any way to close de server just before the hot-reload? Am I doing something wrong, or is there any other possible solution? Thanks!
4 Replies
Apteryx
Apteryx17mo ago
I use tRPC websockets with next.js as well, if you're still having issues ill be happy to share my solution, there are a few steps required to set it up tho
crapthings
crapthings17mo ago
hello how to make websocket work with next.js trpc? can i use socket.io ?
Apteryx
Apteryx17mo ago
why would you use socket.io if youre gonna use trpc?
crapthings
crapthings17mo ago
maybe a high level features like room etc?