pjnicolas
pjnicolas12mo 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
Apteryx12mo 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
crapthings12mo ago
hello how to make websocket work with next.js trpc? can i use socket.io ?
Apteryx
Apteryx12mo ago
why would you use socket.io if youre gonna use trpc?
crapthings
crapthings12mo ago
maybe a high level features like room etc?