Logo Aaryan's Blog

How to pass socket.io to express routes in files?

2 min read

Socket.io 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 socket.io, 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("socket.io");

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) => {
  req.io = io;
  return next();

// Now all routes & middleware will have access to req.io

app.use("/api", require("./routes/api")); // this file's express.Router() will have the req.io 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
Router.post("/new-message", (req, res) => {
  // You can do validation or database stuff before emiting
  req.io.emit("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!