is a popular library used to enable live (real-time) communication across server and client(s). It uses events to receive to transmit data. We’ll be discussing how to use it with Express route files.

We’ll be dealing with the new 3.x version of the, which is a bit different. You can have a look at this migration guide from 2.x to 3.0.

Basically, we create a simple middleware:

const { createServer } = require("http"); // you can use https as well
const express = require("express");
const socketIo = require("");

const app = express();
const server = createServer(app);
const io = socketIo(server, { cors: { origin: "*" } }); // you can change the cors to your own domain

app.use((req, res, next) => { = io;
  return next();

// Now all routes & middleware will have access to

app.use("/api", require("./routes/api")); // this file's express.Router() will have the too.

server.listen(3000, () => console.log(`Server started!`));

This is a much better solution than passing the io to the required import as a functional parameter then utilized by the routes.

How would the api.js file utilize the io? See this example,

const express = require("express");

const Router = express.Router();

// Very simple example"/new-message", (req, res) => {
  // You can do validation or database stuff before emiting"new-message", { content: req.body.content });
  return res.send({ success: true });

module.exports = Router;

You can manage multiple sockets, rooms, or even namespaces.

That’s it!