Understand Why Socket.IO Needs the HTTP Server

One important detail is that Socket.IO must be attached to the HTTP server that handles your Express application.

A common beginner mistake is using app.listen() and then attempting to attach Socket.IO to another HTTP server.

Consider this incorrect implementation:

const app = express();
const io = new Server(createServer(app));

app.listen(3000);

This creates two separate HTTP servers:

  1. The server created by createServer(app) is attached to Socket.IO.
  2. The server created internally by app.listen() handles Express requests.

The Socket.IO server and the Express server are therefore not using the same HTTP server.

Instead, explicitly create one HTTP server and use it for both Express and Socket.IO.

Avoid This Common Mistake

Do not call app.listen() after creating a separate HTTP server for Socket.IO. Start the shared HTTP server using httpServer.listen().

Correct HTTP Server Initialization
import express from 'express';
import { createServer } from 'node:http';
import { Server } from 'socket.io';

const app = express();

const httpServer = createServer(app);

const io = new Server(httpServer);

httpServer.listen(3000);

The same HTTP server is shared between Express and Socket.IO. This allows both HTTP requests and Socket.IO connections to use the same listening port.

Key Takeaways
  • Socket.IO must be attached to the intended HTTP server.

  • Use createServer(app) to create the shared server.

  • Start the application with httpServer.listen().