Next.js Discord

Discord Forum

Nextjs 14.1 socket.io not working

Unanswered
Maine Coon posted this in #help-forum
Open in Discord
Maine CoonOP
Hi all, i'm trying to implement websockets using socket-io in my nextjs14 app. But nothing seems to be working, meaning, nothing is being called... Does next14 even support sockets? Anyway, below is what i've tried. It would be really great if someone provide me a solution.

app/api/socket/route.ts
import { Server } from "socket.io";
import { NextRequest, NextResponse } from "next/server";

export async function GET(req: NextRequest, res: NextResponse) {
  try {
    const io = new Server({
      path: "/api/socket",
      addTrailingSlash: false,
      cors: { origin: "*" },
    });

    io.on("connection", (socket) => {
      console.log("Connected to server");
      const clientId = socket.id;
      console.log("Client Id: " + clientId);
      socket.on("disconnect", () => {
        console.log("Disconnected from server");
      });
    });

    return NextResponse.json({ message: "success" }, { status: 200 });
  } catch (error) {
    return NextResponse.json({ message: error.message }, { status: 500 });
  }
}

app/socket/page.tsx (client)
'use client'
import io, { Socket } from "socket.io-client";

const Chat = () => {
  const [socket, setSocket] = useState<Socket | null>(null);

  useEffect(() => {
    const socketInit = async () => {
      try {
        await fetch("http://localhost:3000/api/socket");
        let connection = io({
          path: "http://localhost:3000/api/socket",
          addTrailingSlash: false,
        });
        setSocket(connection);
      } catch (error) {
        console.error("socket connection error: ", error);
      }
    };

    socketInit();

    return () => {
      if (socket) {
        socket.close();
      }
    };
  }, []);

  return <div className={styles.chatWrapper}>Chat</div>;
};

4 Replies

Toyger
if you are using vercel as hosting then it will not work, here is some more info https://vercel.com/guides/do-vercel-serverless-functions-support-websocket-connections
Buff-breasted Flycatcher
are there any third party services that would support websockets integration with vercel? i.e. something that forwards each websocket message to a serverless function on vercel?
@Buff-breasted Flycatcher are there any third party services that would support websockets integration with vercel? i.e. something that forwards each websocket message to a serverless function on vercel?
Toyger
you can use heroku/railway or any other provider, you can just google are their support websockets.
and then there send queries to your api on vercel.
Maine CoonOP
I wasn't using vercel or anything at the moment, i was just doing a poc but couldn't succeed with nextjs 14...

I had to create a separate node socket server to achieve my goal...