Next.js Discord

Discord Forum

Sockets not working

Unanswered
Toyger posted this in #help-forum
Open in Discord
ToygerOP
I am trying to implement sockets for my dashboard I wanna make and I wanna make it realtime but ive been trying for ages and I tried a ton of stuff (a route using res.socket, a seperate script running the socket and then connecting to it and that worked but it was only http I couldnt get it to be https which is needed by nextjs for some reason and now im trying the route again but its giving address already in use 2999 :catdespair:

8 Replies

ToygerOP
import type { Server as HTTPServer } from "http";
import type { Socket as NetSocket } from "net";
import type { NextApiRequest, NextApiResponse } from "next";
import { NextResponse } from "next/server";
import type { Server as IOServer } from "socket.io";
import { Server } from "socket.io";

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

interface SocketWithIO extends NetSocket {
  server: SocketServer;
}

interface NextApiResponseWithSocket extends NextApiResponse {
  socket: SocketWithIO;
}

export async function GET(_req: NextApiRequest, res: NextApiResponseWithSocket) {
  if (res.socket?.server?.io) {
    return NextResponse.json({
      success: true,
      message: "Socket is already running",
      socket: `:${process.env.SOCKET_PORT}`,
    });
  }

  console.log("Starting Socket.IO server on port:", process.env.SOCKET_PORT);

  const io = new Server({
    path: "/api/socket",
    addTrailingSlash: false,
    cors: { origin: "*" },
  }).listen(Number(process.env.SOCKET_PORT));

  io.on("connect", (socket) => {
    const _socket = socket;
    console.log("socket connect", socket.id);
    _socket.broadcast.emit("welcome", `Welcome ${_socket.id}`);
    socket.on("disconnect", async () => {
      console.log("socket disconnect");
    });
  });

  res.socket.server.io = io;

  return NextResponse.json({
    success: true,
    message: "Socket is started",
    socket: `:${process.env.SOCKET_PORT}`,
  });
}
"use client";

import { useEffect, useState } from "react";
import { io, Socket } from "socket.io-client";

export default function TestPage() {
  const [isConnected, setIsConnected] = useState(false);
  const [lastMessage, setLastMessage] = useState("");
  const [socket, setSocket] = useState<Socket | null>(null);

  useEffect(() => {
    const initSocket = async () => {
      const res = await fetch("/api/socket");
      const data = await res.json();

      if (data.success) {
        const newSocket = io(data.socket, {
          path: "/api/socket",
          addTrailingSlash: false,
        });

        setSocket(newSocket);

        newSocket.on("connect", () => {
          setIsConnected(true);
          console.log("Connected to socket server");
          newSocket.emit("test", "Hello from client");
        });

        newSocket.on("disconnect", () => {
          setIsConnected(false);
          console.log("Disconnected from socket server");
        });

        newSocket.on("welcome", (data) => {
          setLastMessage(data);
          console.log("Received welcome message:", data);
        });

        newSocket.on("connect_error", (error) => {
          console.error("Connection error:", error);
        });

        newSocket.on("error", (error) => {
          console.error("Socket error:", error);
        });
      }
    };

    initSocket();

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

  return (
    <div>
      <h1>Socket.IO Test Page</h1>
      <p>Connection status: {isConnected ? "Connected" : "Disconnected"}</p>
      <p>Last message received: {lastMessage}</p>
    </div>
  );
}
no matter what port I make SOCKET_PORT its always giving address in use
ToygerOP
ig using a custom server solved it but idk if I wanna use a custom server I heard it removes some good nextjs features
@Toyger Next.js serverless functions don’t accommodate long-running connections and that's why you can't use websockets in Next.js natively.
You can try to find other third parties or you can have your custom server.
Or if you are okay with paid hosting you can try this
https://fly.io/javascript-journal/websockets-with-nextjs/
@James4u <@1045011641940574208> Next.js serverless functions don’t accommodate long-running connections and that's why you can't use websockets in Next.js natively. You can try to find other third parties or you can have your custom server.
ToygerOP
I gave up yesterday and used custom server it works it’s just a pain that I gotta restart everything if I change socket instead of hot reload cuz recompiling each change is kinda painful but it’s ok it works
thanks for ur reply tho