Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

184
Views
Socket.io in express js : Router.use requires middleware function but got undefined

I am trying to integrator socket.io in my express js application (Created by express generator).

Here is the answer i've followed

But it didn't worked.

Added following in bin/www

app.io = require('socket.io')();
app.io.attach(server);

When i modify app.use('/', index); with app.use('/', require('./routes/index')(app.io)); in app.js file i got the following error

*

Router.use requires middleware function but got undefined

*

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Here is how you can implement socket.io with express.

var express = require('express')
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);

//serve static files and index.html
app.use(express.static(__dirname + '/'));
app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html'); });

io.on('connection', function(socket){
    //logic handled in here
});

http.listen(7000,function(){ console.log('listening on port: 7000'); });

The above code has one route for handling the serving of index.html, but of course you can extend with additional routes the same way you would in any other app.

Here is how you can have access to socket.io within a route in express generator.

In www:

var server = http.createServer(app);
var io = require('socket.io')(server);
module.exports = {io:io}

Within index.js

router.get('/', function(req, res, next) {
  var io = require('../bin/www')
  console.log('I now have access to io', io)
  res.render('index', { title: 'Express' });
});

Note, the above example is purely showing you how to gain access to the io object within index.js. There are many better ways to require socket.io and pass the io object around, but those decisions seem to be outside the scope of this question.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!