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

261
Views
Socket.io: Cannot read property 'emit' of undefined

So i am trying to connect multiple users to a room where video can be shared, but I keep getting an error whenever I join a room which is Cannot read property 'emit' of undefined which is thrown for the socket.to(roomId).broadcast.emit('user-connected', userId) line. I'm not sure what is causing this, and any help would be great. Cheers.

const express = require('express')
const app = express()
const server = require('http').Server(app)
const io = require('socket.io')(server)
const { v4: uuidV4 } = require('uuid')

app.set('view engine', 'ejs')
app.use(express.static('public'))

app.get('/', (req, res) => {
  res.redirect(`/${uuidV4()}`)
})

app.get('/:room', (req, res) => {
  res.render('room', { roomId: req.params.room })
})

io.on('connection', socket => {
  socket.on('join-room', (roomId, userId) => {
    socket.join(roomId)
    socket.to(roomId).broadcast.emit('user-connected', userId)
    // This line here

    socket.on('disconnect', () => {
      socket.to(roomId).broadcast.emit('user-disconnected', userId)
    })
  })
})

server.listen(3000)
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

To broadcast to all clients in a particular room, just use socket.to(roomId).emit(...). You don't need to use the .broadcast property.

over 4 years ago · Santiago Trujillo Report

0

If I am right, you are following Web Dev Simplified's Zoom Clone video, I was facing the same issue, but omitting the .broadcast property works fine.

over 4 years ago · Santiago Trujillo Report

0

socket.broadcast.to(roomId).emit("user-connected", userId);

It worked for me

over 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!