Next.js Discord

Discord Forum

socket.io is stuck in infinite loop for connection

Unanswered
Labrador Retriever posted this in #help-forum
Open in Discord
Labrador RetrieverOP
I'm using socket.io, and the connection is happening but I think it is getting disconnected as soon as it is getting connected and I can see the requests being made from the browser tab, and its inifinitely making request to websocket.

9 Replies

Labrador RetrieverOP
Also this is what happens when I test the connection from postman for socket.io, it says disconnected but i can see the server log saying connected and its socket.id as I have set the console log in io.on(connection.. in api
@@ts-ignore show the code where you're doing the io.on(...)
Labrador RetrieverOP
Here, this is the whole code, its on pages/api/ws and Im using app directory for other, only websocket is on pages dir

import { Server as NetHttpServer } from 'http';
import { Server as NetServer, Socket } from 'net';
import { NextApiRequest, NextApiResponse } from 'next';
import { Server as ServerIO } from 'socket.io';

export const config = {
  api: {
    bodyParser: false,
  },
};

export type NextApiResponseServerIo = NextApiResponse & {
  socket: Socket & {
    server: NetServer & {
      io: ServerIO;
    };
  };
};

const ioHandler = (req: NextApiRequest, res: NextApiResponseServerIo) => {
  if (!res.socket.server.io) {
    const path = '/api/ws';
    const httpServer: NetHttpServer = res.socket.server as any;
    const io = new ServerIO(httpServer, {
      // path: path,
      // addTrailingSlash: false,
      transports: ['websocket'],
    });
    res.socket.server.io = io;

    io.on('connection', (socket) => {
      console.log('connected', socket.id);
    });
  }

  res.end();
};

export default ioHandler;
@@ts-ignore but using socketio in api routers isn't a good idea this won't word on serverless providers like vercel
Labrador RetrieverOP
yeah, I wont be deploying it on vercel, so wont be a problem
@@ts-ignore the res.end() ig
Labrador RetrieverOP
commenting that out also doesnt do anything
everything looks fine ig
Labrador RetrieverOP
yeah, it looks fine but isnt working right...