title: SocketIO with Nextjs deployed to Vercel, socket is not connecting
body: <p>I am trying to create a next app that also communicates with its backend in realtime with a socket, and I am using <code>socket.io</code> for that. It is all working just fine locally (even when built), but when deployed to vercel, I get errors of the type of <code>WebSocket connection to '&lt;URL&gt;' failed: WebSocket is closed before the connection is established.</code></p>
  <p>First I created a custom Nextjs server:</p>
  <pre><code>import { createServer } from &quot;http&quot;;
  import { parse } from &quot;url&quot;;
  import { Server as SocketIOServer, Socket } from &quot;socket.io&quot;;
  import next from &quot;next&quot;;
  
  const port = parseInt(process.env.PORT || &quot;3000&quot;, 10);
  const dev = process.env.NODE_ENV !== &quot;production&quot;;
  const app = next({ dev });
  const handle = app.getRequestHandler();
  
  console.log(&quot;hello&quot;);
  
  app.prepare().then(() =&gt; {
    const server = createServer((req, res) =&gt; {
      const parsedUrl = parse(req.url!, true);
      handle(req, res, parsedUrl);
    }).listen(port);
  
    // tslint:disable-next-line:no-console
    console.log(
      `&gt; Server listening at http://localhost:${port} as ${
        dev ? &quot;development&quot; : process.env.NODE_ENV
      }`
    );
  
    const socketIO = new SocketIOServer(server, { transports: [&quot;websocket&quot;] });
  
    socketIO.on(&quot;connection&quot;, (socket: Socket) =&gt; {
      console.log(&quot;connected&quot;, socket.id);
    });
  });
  </code></pre>
  <p>Then on the frontend:</p>
  <pre><code>import { io } from &quot;socket.io-client&quot;;
  
  useEffect(() =&gt; {
    const socket = io(window?.location?.hostname || &quot;http://localhost:3000&quot;, {
      reconnectionDelay: 1000,
      reconnection: true,
      reconnectionAttempts: 10,
      transports: [&quot;websocket&quot;],
      agent: false,
      upgrade: false,
      rejectUnauthorized: false
    });
  
    socket.on(&quot;connect&quot;, () =&gt; {
      console.log(&quot;someone connected: &quot;, socket?.id);
    });
  }, []);
  </code></pre>
  <p>This code works just great locally, no issues at all, both in <code>dev</code> mode and <code>build &amp;&amp; start</code>, both work just fine.</p>
  <p>The problems start, once it is deployed to vercel.</p>
  <p>If I do not add <code>&quot;:3000&quot;</code> to the <code>window.location.hostname</code> I get error:</p>
  <p><code>WebSocket connection to 'wss://xxxxxx.vercel.app/socket.io/?EIO=4&amp;transport=websocket' failed: doOpen</code></p>
  <p>If I add it, then it becomes:</p>
  <p><code>WebSocket connection to 'wss://xxxxxx.vercel.app:3000/socket.io/?EIO=4&amp;transport=websocket' failed: WebSocket is closed before the connection is established.</code></p>