Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 36 ยท Integration with Frameworks

Socket.IO with Express and HTTP Servers

Attach Socket.IO to an Express app, share sessions and middleware with sockets, push events from REST routes to rooms, and avoid common integration mistakes.

Most real apps are not only WebSockets. They have a REST or HTML side (login, uploads, webhooks) and a real-time side. Socket.IO is designed to share one HTTP server with a web framework such as Express, Fastify or Koa. This lesson uses Express, and the same ideas apply elsewhere: attach to the HTTP server, reuse authentication, and let normal routes push events to connected clients.

Express and Socket.IO are not installed in the runner on this site. Real code is read-only. The runnable example uses a real node:http server on the loopback address with a small hand-written socket stand-in.

One HTTP server, two protocols

JavaScript
import express from "express";
import { createServer } from "node:http";
import { Server } from "socket.io";

const app = express();
const httpServer = createServer(app);   // not app.listen()!
const io = new Server(httpServer);

app.get("/", (req, res) => res.send("hello"));

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

httpServer.listen(3000);

The classic mistake is app.listen(3000) and then handing app to Socket.IO. app.listen creates a different HTTP server, so Socket.IO would be attached to something that is not listening. Create the HTTP server yourself with createServer(app), give that to new Server(...), and call httpServer.listen.

Socket.IO answers requests under the path /socket.io/ (configurable with the path option) and ignores everything else, so your routes keep working. It also serves its own client bundle at /socket.io/socket.io.js, which is why <script src="/socket.io/socket.io.js"></script> works in a page served by the same host.

Pushing events from REST routes

A very common shape: a client sends an HTTP request (a form post, a webhook from a payment provider), and the server wants to notify browsers in real time. Make the io instance reachable from your routes:

JavaScript
app.set("io", io);

app.post("/orders/:id/ship", express.json(), (req, res) => {
  const order = shipOrder(req.params.id);
  req.app.get("io").to(`order:${order.id}`).emit("order:shipped", { id: order.id, at: order.shippedAt });
  res.status(204).end();
});

io.on("connection", (socket) => {
  socket.on("order:watch", (id) => socket.join(`order:${id}`));
});

Browsers join order:123, the webhook route emits to that room, and every watcher updates. The HTTP route and the socket handlers never talk to each other directly: the room is the meeting point.

Node.js A REST route pushing to a room (real HTTP, stand-in sockets)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Only the clients that joined order:7 were notified. In production the same pattern works across servers once you add an adapter.

Sharing middleware and sessions

Socket.IO runs on top of an engine (Engine.IO) that handles the HTTP part of the connection. Since 4.6 you can run Express-style middleware on every request the engine sees, with io.engine.use. This is the standard way to reuse a session or a security middleware for sockets.

JavaScript
import session from "express-session";
import helmet from "helmet";

const sessionMiddleware = session({
  secret: process.env.SESSION_SECRET,
  resave: false,
  saveUninitialized: false,
  cookie: { httpOnly: true, sameSite: "lax", secure: true },
});

app.use(sessionMiddleware);
io.engine.use(sessionMiddleware);                 // same session for sockets
io.engine.use(helmet());                           // security headers on engine requests

io.on("connection", (socket) => {
  const session = socket.request.session;          // the Express session
  if (!session?.userId) return socket.disconnect(true);
  socket.join(`user:${session.userId}`);
});

socket.request is the HTTP request of the handshake, so cookies and the session are available there. Keep in mind that the session is read when the connection is established. If the user logs out later, the open socket still holds the old values, so you must disconnect their sockets on logout:

JavaScript
app.post("/logout", (req, res) => {
  const userId = req.session.userId;
  req.session.destroy(() => {
    io.in(`user:${userId}`).disconnectSockets(true);   // close all of the user's sockets
    res.redirect("/");
  });
});

Authentication strategies, tokens and namespaces are covered in the Middleware and Authentication chapter. For session-less APIs, a JWT passed in the handshake auth object is the usual alternative.

Express middleware versus Socket.IO middleware

They are different systems, easy to confuse:

Express middleware io.engine.use io.use
Runs for Every HTTP request of your app Every HTTP request handled by the engine (polling, upgrade) Each new Socket.IO connection, per namespace
Signature (req, res, next) (req, res, next) (socket, next)
Good for Routes, body parsing Sessions, CORS, headers Auth, logging, rate limits per connection

Running next to other frameworks

  • Fastify: pass fastify.server (the underlying Node server) to new Server(...), or use a plugin such as fastify-socket.io that does it for you.
  • Koa, Hapi, plain http: all expose a Node http.Server; Socket.IO attaches to it.
  • NestJS: has a @WebSocketGateway decorator with a Socket.IO adapter (@nestjs/platform-socket.io); gateways map @SubscribeMessage handlers to events.
  • Serverless platforms that cannot hold long-lived connections are a poor fit for Socket.IO servers. Use a host that supports persistent processes.

A path option is useful when the real-time endpoint must sit behind a prefix:

JavaScript
const io = new Server(httpServer, { path: "/realtime/" });
// client: io({ path: "/realtime/" })

Both sides must agree on the path, and trailing slashes matter: the default is /socket.io/.

Frontend serving

For small apps, the same Express app can serve the page and static files:

JavaScript
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";

const __dirname = dirname(fileURLToPath(import.meta.url));
app.use(express.static(join(__dirname, "public")));

In a bundler-based frontend you install socket.io-client and import io from it. The next lessons cover typed events and browser clients.

Common mistakes

  • Using app.listen instead of the HTTP server you gave to Server.
  • Forgetting CORS when the page and the socket server are on different origins (see security hardening).
  • Creating a new Server per request or per route. There is one io per process.
  • Emitting from a route before the client joined the room: events are not buffered for the future.
  • Trusting socket.request.session after logout without disconnecting sockets.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should you create the server with createServer(app) instead of calling app.listen()?

    app.listen creates its own HTTP server. Socket.IO needs the server instance that you later call listen on.
  2. 2. What is the purpose of io.engine.use(sessionMiddleware)?

    Engine-level middleware sees the handshake request, so the session is loaded and available on socket.request.
  3. 3. A user logs out in Express. What should you also do?

    Open sockets keep the identity from handshake time, so you must close them explicitly, e.g. io.in('user:'+id).disconnectSockets(true).
  4. 4. Which signature does io.use middleware have?

    Socket.IO connection middleware receives the socket and a next function, unlike Express middleware.

Summary

  • Attach Socket.IO to the HTTP server you create with createServer(app).
  • Routes can push events with io.to(room).emit(...); rooms connect HTTP and real-time sides.
  • Use io.engine.use to share sessions and security middleware with sockets.
  • Disconnect sockets on logout; identity is fixed at handshake time.
  • Express, engine and io.use middleware are three different layers.

Next: Typed Events with TypeScript