f in x
WebSocket with Socket.io for real-time chat and push notifications – code, costs, and pitfalls
> cd .. / HUB_EDITORIALE
Sviluppo di siti web

WebSocket with Socket.io for real-time chat and push notifications – code, costs, and pitfalls

[2026-07-12] Author: Ing. Calogero Bono
Zenithby Meteora Web The operating system for your business. Social, clients, bookings and invoices in one platform. Gyms, barbers, professionals. Discover Zenith Free demo · no card

Why your HTTP polling is burning bandwidth (and revenue)

If you're building a chat, live dashboard, or real-time notifications, the first instinct is often: "Let me AJAX every 2 seconds." We see this constantly in projects that come to us. Blind polling costs bandwidth, loads the server, and – worst case – crashes the database when 500 users query a messages table simultaneously. WebSocket with Socket.io solves it with a persistent bidirectional connection. At Meteora Web, we have been using it for years on proprietary platforms: we built a live notification system for a retail chain, cutting HTTP requests by 97% and DB load by 70%. Direct infrastructure savings? Around €40/month on a VPS. Doesn't sound much? Multiply by 100 clients and it's €4,000/year.

What makes Socket.io different from bare WebSocket?

Raw WebSocket is like a direct cable between client and server: efficient, but without airbags. Socket.io adds: automatic fallbacks (long-polling if WebSockets are blocked), rooms to separate user groups, custom events, automatic reconnection, and broadcasting. You don't need to reinvent the wheel for handling disconnections, mobile clients with hostile NATs, or corporate proxies. For an SME, that means fewer debug hours and more time for business.

But it's not a silver bullet

Socket.io has overhead compared to native WebSocket, but for 99% of cases it's negligible. We always recommend it as a starting point. If you need sub-millisecond latency (trading, gaming), we evaluate alternatives like ws or uWebSockets. But for chat, notifications, real-time collaboration, Socket.io is the right choice.

Sponsored Protocol

How to build a real-time chat with Socket.io?

Here's a practical example: a Node.js backend with Express, a vanilla frontend, and Socket.io. The code is ready to copy-paste and run.

Installation

npm init -y
npm install express socket.io

Server (server.js)

const express = require('express');
const http = require('http');
const { Server } = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = new Server(server, {
  cors: { origin: '*', methods: ['GET', 'POST'] }
});

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
  console.log('User connected:', socket.id);

  socket.on('chat message', (msg) => {
    console.log('Message received:', msg);
    io.emit('chat message', { user: socket.id, text: msg });
  });

  socket.on('disconnect', () => {
    console.log('User disconnected:', socket.id);
  });
});

server.listen(3000, () => {
  console.log('Server listening on http://localhost:3000');
});

Client (index.html)



Realtime Chat

  

    Run with node server.js and open two windows on localhost:3000. Type in one – the message appears in the other. Simple, immediate, functional. Now you can extend it with rooms, authentication, and database persistence.

    Sponsored Protocol

    How to manage push notifications with Socket.io without wasting resources?

    Push notifications differ from chat because they often need to reach specific users or groups. With Socket.io we use rooms. After login, each user joins a room identified by their ID or role. When an event triggers (new order, admin message), we emit only to the correct room. This avoids flooding 10,000 clients with irrelevant data.

    Sponsored Protocol

    Example: single-user notification

    // During connection, after authentication
    socket.on('join', (userId) => {
      socket.join(`user:${userId}`);
    });
    
    // Elsewhere in the server, when an event occurs
    const userId = '123';
    io.to(`user:${userId}`).emit('notification', {
      type: 'new_order',
      message: 'You have a new order!',
    });

    Security note: never trust the client to decide which room to join. Always validate the user ID server-side after authentication.

    How much does a Socket.io server cost compared to polling? (Let's crunch the numbers)

    We come from accounting, so we always look at numbers. Take an app with 200 simultaneous users. With polling every 5 seconds, each minute generates 200 x 12 = 2,400 HTTP requests. With Socket.io, one WebSocket connection stays open and only exchanges actual messages. In a low-traffic chat (one message per user every 30 seconds), that’s about 400 messages per minute versus 2,400 requests. Server load drops by 83%. On a €20/month VPS, direct savings are modest, but scaling to 2,000 simultaneous users, polling would require a bigger server (€40) while Socket.io handles it on the same one. Plus, network traffic is much lower – a big difference on consumption-based hosting (e.g., AWS). At Meteora Web, we moved a client from €4,000/year infrastructure to €1,200/year just by switching to WebSocket.

    Sponsored Protocol

    Security: what should you never forget? (Mistakes we see every day)

    We say it often: security in SMEs is systematically underestimated. With Socket.io the risks are: event injection (a client can emit events it shouldn't), room sniffing, and DoS if connections aren't limited. Here are the essential countermeasures:

    • Validate all events server-side: never execute socket.emit('admin:deleteUser', data) without checking permissions.
    • Mandatory authentication: use a middleware to verify JWT tokens before connection.
    • Rate limiting: limit how many events a client can emit per minute (e.g., max 10 chat messages per minute).
    • Event whitelist: accept only known events, ignore the rest.
    • HTTPS/WSS required: no plain WebSocket in production.

    How to integrate Socket.io with your existing stack (Laravel, React, Vue)?

    Socket.io is frontend-agnostic. You can use it with React via the socket.io-client package, Vue, or even a mobile app. We integrated it into a Laravel + Livewire app for live notifications: the Laravel backend fires events to a dedicated Node.js server, which acts as a WebSocket bridge. Works perfectly and doesn't require rewriting the entire backend in Node. If your backend is already Node.js (maybe with Express, like the example), Socket.io integrates directly. For the frontend, the vanilla code above works – same principle applies to React with useEffect and socket.io-client.

    Sponsored Protocol

    What to do now

    1. Try the example above: install Node, create the server, and test locally in 5 minutes. It's the fastest way to understand the power of real-time.
    2. Analyze your current app: how many HTTP requests do you make for real-time updates? Calculate potential savings. If you don't have metrics yet, add a counter (e.g., Express middleware) and track for a week.
    3. Add authentication and rate limiting: before going to production, implement the security measures described above. We have a ready module we can adapt, but a custom middleware is also simple.
    4. Evaluate the architecture: if your backend is PHP/Laravel, consider a Node.js sidecar for WebSocket. If you already use Node, integrate Socket.io directly into your project.
    5. Check with your hosting provider: verify that the VPS supports persistent WebSocket connections (some cheap plans have aggressive timeouts). We recommend DigitalOcean or Hetzner for good value.

    At Meteora Web, we work daily with these technologies and help SMEs implement real-time solutions without waste. To go deeper, our pillar on Node.js is a good starting point. For security best practices, check the official Socket.io middleware documentation.

    Ing. Calogero Bono

    > AUTHOR_EXTRACTED

    Ing. Calogero Bono

    Ingegnere informatico, fondatore di Meteora Web e Zenith OS. System administrator e progettista di piattaforme, app e CMS proprietari, con esperienza in sviluppo full-stack, marketing digitale ed ecosistema Google.
    [ Read Full Dossier ]

    > METEORA_WEB // DIGITAL AGENCY

    We build the digital presence your business deserves.

    Websites, social media, online advertising, e-commerce and high-performance hosting, engineered with method by computer engineers in Sciacca, for all of Italy.

    > MW_JOURNAL

    > READ_ALL()