Socket.io how to send JavaScript object

Viewed 87141

How to send JavaScript Object with Socket.io from server to client? I'm using Socket.io as WebSocket(sending with .send() and listen with message event). When I'm trying to do something like on server-side:

var myObject = {
    message: 'Hello World!'
}

socket.send(myObject);

on client-side I'm getting only this String: [object Object]

5 Answers

In socket.io V4.x, there is no need to use JSON.stringify():

There is no need to run JSON.stringify() on objects as it will be done for you.

e.g.

// BAD
socket.emit("hello", JSON.stringify({ name: "John" }));

// GOOD
socket.emit("hello", { name: "John" });

more info on this link.

Related