Ticker

6/recent/ticker-posts

⚡ WebSockets in JavaScript – Real-Time Without the Jugaad

⚡ WebSockets in JavaScript – Real-Time Without the Jugaad

You ever tried building something “real-time” using setInterval?

Like:

  • chat app
  • notifications
  • live scores

And you keep hitting the API every 2 seconds like:

👉 “anything new? … anything now? … now?”

It works… but it feels wrong 😅

That’s basically where WebSockets come in. Instead of asking again and again, you just stay connected and data flows whenever it’s ready.

⚡ So what’s actually different?

Normal HTTP is like:

👉 ask → get response → connection closed

Every. single. time.

WebSockets?

👉 connect once → keep it open → both sides talk whenever

No repeated requests. No polling nonsense.

🔎 Basic setup (nothing fancy)

const socket = new WebSocket("wss://example.com");

And then you just listen:

socket.onopen = () => {
  console.log("connected");
};

socket.onmessage = (event) => {
  console.log("server says:", event.data);
};

socket.onclose = () => {
  console.log("disconnected");
};

That’s literally enough to get started.

📤 Sending data (simple but important)

socket.send(JSON.stringify({
  type: "chat",
  message: "hello 👋"
}));

Yeah… always send JSON.

If you start sending random strings, future-you will suffer.

🔥 Real example (chat-ish logic)

const socket = new WebSocket("wss://chat.example.com");

socket.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log(data.message);
};

function sendMessage(msg) {
  socket.send(JSON.stringify({ message: msg }));
}

Nothing crazy. This is basically how most chat features begin.

💡 Real Developer Insight

Here’s the part no one tells beginners clearly:

👉 WebSockets are not “better” than HTTP.
They’re just different.

I’ve seen people use WebSockets for stuff like:

  • loading user profile
  • fetching static data

That’s overkill.

Where it actually makes sense:

  • chat
  • live dashboards
  • multiplayer stuff
  • collaborative editing

If your data doesn’t need to update instantly, just use fetch and move on.

⚠️ Where things start breaking (real-world pain)

This is the part you’ll hit in production.

1. Connections drop. A lot.

Network changes, tab sleeps, mobile switching… boom 💀

If you don’t handle reconnect, your app just silently stops working.

function connect() {
  const socket = new WebSocket("wss://example.com");

  socket.onclose = () => {
    console.log("lost connection… retrying");
    setTimeout(connect, 3000);
  };
}

connect();

You need something like this.

2. You don’t get request/response structure

It’s all events.

So you need to define your own “protocol”:

{ type: "message", payload: {...} }

Otherwise everything becomes chaos very fast.

3. Scaling gets tricky

One user = one connection.

Now imagine:

👉 10,000 users = 10,000 open connections

Yeah… backend needs to handle that properly.

This is where tools like Socket.IO, Redis pub/sub, etc., usually come in.

⚠️ Common mistakes (I’ve seen all of these)

Using WebSockets for everything
→ unnecessary complexity

No reconnect logic
→ app breaks silently

Multiple connections per page
→ memory + performance issues

Sending unstructured data
→ debugging nightmare later

🚀 Best Practice Summary

✅ Use WebSockets only when you truly need real-time updates
✅ Always implement reconnect logic (connections will drop)
✅ Stick to structured JSON messages
✅ Keep a single connection per app
✅ Don’t replace HTTP with WebSockets blindly

Reactions

Post a Comment

0 Comments