#Socket.io with next 13

2 messages · Page 1 of 1 (latest)

bitter hill
#

I'm new into web dev, I'm building a simple chat app in next13 ,how will i implement sockets in it, i would need routes i suppose,but how? please guide and if can give example, please do!

zenith latch
#

For the client, Socket.io's documentation is enough.
https://socket.io/how-to/use-with-react

I'm copypasting my own implementation from typescript, so convert to javacript if needed
For the server, create a (src)/pages/api/socketio.ts, and paste this:

interface SocketServer extends HTTPServer {
  io?: IOServer | undefined
}

interface SocketWithIO extends NetSocket {
  server: SocketServer
}

interface NextApiResponseWithSocket extends NextApiResponse {
  socket: SocketWithIO
}

export default function handler(_: NextApiRequest, res: NextApiResponseWithSocket) {
    if (res.socket.server.io) {
        console.log("[Server Socket] > Socket Server is already running");
    } else {
        console.log("[Server Socket] > Socket Server is initializing");
        const io: Server<ClientToServerEvents, ServerToClientEvents> = new Server(
            res.socket.server,
            {
                cors: {
                    origin: "http://localhost:3000"
                },
                connectionStateRecovery: {
                    // The backup duration of the sessions and the packets
                    maxDisconnectionDuration: 2 * 60 * 1000,
                    // Whether to skip middlewares upon successful recovery
                    skipMiddlewares: false,
                },
            }
        );

        io.on("connection", (socket) => {
            // Socket event handlers goes here
        });

        res.socket.server.io = io;
    }
    res.end();
}

Note: This works on version of Next.js before 13.3.0. There is issues pass 13.3.0 and there is already a thread here: https://discord.com/channels/752553802359505017/1104022615439462400

This guide shows how to use Socket.IO within a React application.