Use socket.io in expressjs routes instead of in main server.js file
There are multiple ways to share the io
variable with route files.
When you
require()
in your route file, pass it theio
variable as a constructor argument.Use
app.set("io", io)
so you can then uselet io = app.get("io")
in any file that has access to theapp
object.Create a middleware that puts the
io
object on everyreq
object so you can access it from there any time.
Here's an example of passing it as a constructor argument to the router file:
let server = app.listen(3000);let io = require('socket.io')(server);// load other routersapp.use(require("./someRouterFile.js")(io));// in someRouterFile.jsconst express = require('express');module.exports = function(io) { let router = express.Router() // define routes // io is available in this scope router.get(...) return router;}
Here's an example of the app.set()
scheme:
let server = app.listen(3000);let io = require('socket.io')(server);app.set("io", io);
Then, anywhere in your routes that you have access to the app
object, you can get it with:
let io = app.get("io");
Here's an example of using a middleware to set the io
object onto every req
object so it's available from all routes.
let server = app.listen(3000);let io = require('socket.io')(server);// place this middleware before any other route definitions// makes io available as req.io in all request handlersapp.use(function(req, res, next) { req.io = io; next();});// then in any express route handler, you can use req.io.emit(...)
Here's an example of using an argument to the module constructor without middleware:
// in mysocket.jsmodule.exports = (io) => { console.log('IO: ', io); io.on('connect', socket => { // handle various socket connections here }); // put any other code that wants to use the io variable // in here};
Then, in your main file:
let server = app.listen(3000);let io = require('socket.io')(server);// initialize my socketio module and pass it the io instancerequire('./mysocket.js')(io);
In server.js:
module.exports.getIO = function(){ return io;}
In your route file:
var theServer = require('<path to server.js>');var iovar = theServer.getIO(); //your io var
Sharing my Solution that I've used
Another solution for this problem (that I actually used) is that we can make our io
(socket.io
object) object global.
Simply assign io
to the global.io
.
The io
object is in index.js
, after creating and setting up the io
object simply do global
(i-e global.io = io;
), now this io
object is accessible in any route that we are working within our project.