Node server keep shutting down when I start typing message

I am making a chat app, but when I write a message and press send, my node server keep giving me:

TypeError: Cannot read property 'trim' of undefined

or

TypeError: Cannot read property 'room' of undefined

Then it crashes, I don’t know why, everything else was working normally, only the server crashes. I’ve tried fixing it myself to no avail, without the server, you can probably guess what will happen.

Here’s the code:

index.js:


var express = require ('express')

var http = require ('http')

var { addUser, removeUser, getUser, getUsersInRoom } = require ('./user')


var router = require ('./router')

var { callbackify } = require('util')


var PORT = process.env.PORT || 5000


var app = express()

var server = http.createServer(app)

var io = require('socket.io')(server, {
  cors: {
    origin: '*',
  }
});

app.use(router)

io.on('connection', (socket) => {
    socket.on('join', ({ name, room }, callback) =>{
    var { error, user } = addUser({ id: socket.id, name, room })


    if(error) return callback(error)

    socket.emit('message', { user: 'admin', text: `Now, I- Oh, ${user.name}, welcome to room ${user.room},enjoy your time here!` })
    socket.broadcast.to(user.room).emit('message',{user: 'admin', text:`Hey, just coming in to say ${user.name} joined, also, how you guys doin.`})

    socket.join(user.room)

    callback()
  })

  socket.on('sendMessage', (message, callback) => {
    var user = getUser(socket.id)


    io.to(user.room).emit('message', { user: user.name, text: message })

    callback()
  })

    socket.on('disconnect', () => {
        console.log('Aw they left :(');

      });
  });

server.listen(PORT, () => console.log (`This is Index, port ${PORT} secured, lots of unfixable bug`))

user.js(where the problem exist):

const users = []

const addUser = ({ id, name, room }) =>{
  name = name.trim().toLowerCase()
  room = room.trim().toLowerCase()

  const existingUser = users.find((user) => user.room === room && user.name === name)

  if(existingUser){
      return {error: 'Username is already taken you dumbass'}
  }

  const user = {id, name, room}

  users.push(user);

  return{ user }
}
const removeUser = (id) =>{
  const index = users.findIndex ((user) => user.id === id)

if(index !== -1) {
    return users.splice(index, 1)[0]
}
}

const getUser = (id) => users.find((user) => user.id === id)

const getUsersInRoom = (room) => users.filter((user) => user.room === room)

module.exports = { addUser, removeUser, getUser, getUsersInRoom }

and router.js:

const express = require('express')
const router = express.Router();

router.get('/*', (req,res) =>{
    res.send(`Server is up and running`)
})

module.exports = router;

That is all the server file because the problem comes from server, not client (there is not enough words in here so I have to do this) Thanks in advance!

Answer

Both error is due to the application is trying to access a subfunction/subparameter of an undefined value.

Are you sure the client is sending the right param when emitting “join” ? what you can do on the server side is do some validation and check if its undefined and set a default value if it is.

name = name ? name.trim().toLowerCase() : "default_name";
room = room ? room.trim().toLowerCase() : "default_room";

as for the Room of undefined error is most likely due to this part of the app

const existingUser = users.find((user) => user.room === room && user.name === name)

try checking if users.length, if it’s 0 then don’t bother doing .find(), or you can add validation inside the .find() function to check if user is undefined,then return false;

const existingUser = users.find((user) => user && user.room === room && user.name === name)