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

216
Views
socket.io - TypeError: Cannot read property 'join' of undefined

I'm trying to create a room when a post request to /room/create, but I get this error: TypeError: Cannot read property 'join' of undefined. I have created a middleware that lets me use the io object in a request, but apparently it still doesn't work.

server.js:

const express = require("express");
const app = express();
const { createServer } = require("http");
const { Server } = require("socket.io");
const port = process.env.PORT || 5000;
const httpServer = createServer(app)

const roomRouter = require("./routers/roomRouter")

const io = new Server(httpServer, {
  cors:{
    origin: "http://localhost:3000",
    methods: ["GET", "POST"]
  }
})

io.on("connection", (socket) => {
  console.log(socket.id);
})

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

httpServer.listen(port, () => {
  console.log(`Listening on port ${port}`);
})

app.use("/room", roomRouter) 

app.use((req, res) => {
  res.status(404).send("URL not found!");
});

roomRouter.js:

const express = require("express")
const router = express.Router()

router.post("/create", async(req, res, next) => {
    try {
        // This line causes the error:
        req.io.socket.join("room1")
        const id = 27432
        res.status(201).json({id: id})
    } catch (err) {
        console.log(err);
        res.status(500).json({error: err})
    }
})

module.exports = router 
about 4 years ago · Juan Pablo Isaza
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!