← Back to Blog
How to use the wsocket.io SDK: Node.js (Publisher) + JavaScript (Subscriber) — Complete guide with examples
· 18 min read ·

How to use the wsocket.io SDK: Node.js (Publisher) + JavaScript (Subscriber) — Complete guide with examples

Practical tutorial on integrating the wsocket.io SDK in your project: publish events from Node.js on the backend and receive them in real-time in the browser with JavaScript. Pub/Sub, channels, presence, history and wildcards.

#wsocket#websocket#nodejs#javascript#sdk#realtime#pubsub#tutorial
Share

If you need realtime communication in your application — chat, live dashboards, notifications, IoT — wsocket.io solves it with 5 lines of code. In this guide I show how to use the Node.js SDK (publisher/backend) and the JavaScript SDK (subscriber/browser) from scratch to production.

TL;DR: Install the SDK, connect with your API key, publish to channels and receive events in the browser. No WebSocket server to maintain, no Redis to configure, no reconnection headaches.


What is wsocket.io?

wsocket.io is a realtime infrastructure platform that offers:

  • Pub/Sub with channels — publish from any backend, receive on any frontend
  • Presence — know who is online in real-time
  • History — replay missed messages
  • Push Notifications — Web Push, FCM, APNs
  • Webhooks — HTTP callbacks signed with HMAC-SHA256
  • 16 SDKs — Node.js, Python, Go, Rust, Java, C#, PHP, Ruby, Kotlin, Swift, Dart, Elixir, C, C++, Pascal

Average latency < 5ms. Free tier with 100 connections and 10K messages/day.


1. Creating your account and API Key

  1. Go to wsocket.io/register and create a free account
  2. In the dashboard, click “Create App”
  3. Copy the generated API Key (format: wsk_...)
# Your API Key will look like:
wsk_live_abc123def456...

2. Installing the SDK on Node.js (Backend/Publisher)

npm install @wsocket-io/sdk

Or with yarn/pnpm:

yarn add @wsocket-io/sdk
# or
pnpm add @wsocket-io/sdk

Basic connection

// server.js
const { WSocket } = require('@wsocket-io/sdk');

const client = new WSocket({
  url: 'wss://node00.wsocket.online',
  apiKey: 'wsk_live_YOUR_API_KEY'
});

await client.connect();
console.log('✅ Connected to wsocket.io');

Publishing to a channel

// Publish a message to the "chat:general" channel
const channel = client.channel('chat:general');

await channel.publish({
  user: 'Alice',
  text: 'Hello everyone! 🚀',
  ts: Date.now()
});

Publishing direct messages

// Direct message to a specific user
const inbox = client.channel('user:bob:inbox');

await inbox.publish({
  type: 'dm',
  from: 'Alice',
  text: 'Private message!',
  ts: Date.now()
});

3. Integrating with Express.js

The most common use case is publishing events from a REST API:

// routes/notifications.js
const express = require('express');
const { WSocket } = require('@wsocket-io/sdk');
const router = express.Router();

const ws = new WSocket({
  url: 'wss://node00.wsocket.online',
  apiKey: process.env.WSOCKET_API_KEY
});

// Connect once at startup
ws.connect();

// POST /api/notify — publish event to all subscribers
router.post('/notify', async (req, res) => {
  const { channel, message } = req.body;

  await ws.channel(channel).publish({
    ...message,
    ts: Date.now()
  });

  res.json({ ok: true, channel });
});

// POST /api/order-update — notify order status
router.post('/order-update', async (req, res) => {
  const { orderId, status } = req.body;

  await ws.channel(`order:${orderId}`).publish({
    event: 'status_changed',
    status,  // 'confirmed' | 'preparing' | 'shipped' | 'delivered'
    ts: Date.now()
  });

  res.json({ ok: true });
});

module.exports = router;

4. JavaScript SDK in the Browser (Subscriber)

On the frontend, the simplest approach is native WebSocket:

<!-- index.html -->
<script>
  const API_KEY = 'wsk_live_YOUR_API_KEY';
  const ws = new WebSocket(`wss://node00.wsocket.online/?key=${API_KEY}`);

  ws.onopen = () => {
    console.log('✅ Connected');

    // Subscribe to a channel
    ws.send(JSON.stringify({
      action: 'subscribe',
      channel: 'chat:general'
    }));
  };

  ws.onmessage = (event) => {
    const msg = JSON.parse(event.data);

    if (msg.action === 'message') {
      console.log('📩 New message:', msg.data);
      // Render to the DOM...
    }
  };

  ws.onclose = () => {
    console.log('🔌 Disconnected — reconnecting...');
    // Implement reconnection logic
  };
</script>
npm install @wsocket-io/sdk
// app.js (React, Vue, Svelte, etc.)
import { WSocket } from '@wsocket-io/sdk';

const client = new WSocket({
  url: 'wss://node00.wsocket.online',
  apiKey: 'wsk_live_YOUR_API_KEY'
});

await client.connect();

// Subscribe to a channel
const channel = client.channel('chat:general');

channel.on('message', (data) => {
  console.log('New message received:', data);
});

// Subscribe to multiple channels with wildcards
client.channel('notifications:*').on('message', (data) => {
  console.log('Notification:', data);
});

5. Full example: Real-time chat

Backend (Node.js + Express)

// server.js
const express = require('express');
const { WSocket } = require('@wsocket-io/sdk');

const app = express();
app.use(express.json());

const ws = new WSocket({
  url: 'wss://node00.wsocket.online',
  apiKey: process.env.WSOCKET_API_KEY
});
ws.connect();

// Send chat message
app.post('/api/chat/send', async (req, res) => {
  const { room, user, text } = req.body;

  await ws.channel(`chat:${room}`).publish({
    user,
    text,
    ts: Date.now()
  });

  res.json({ ok: true });
});

app.listen(3000, () => console.log('Server running on port 3000'));

Frontend (React)

// Chat.jsx
import { useEffect, useState, useRef } from 'react';

export function Chat({ room, apiKey }) {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const wsRef = useRef(null);

  useEffect(() => {
    const ws = new WebSocket(`wss://node00.wsocket.online/?key=${apiKey}`);

    ws.onopen = () => {
      ws.send(JSON.stringify({
        action: 'subscribe',
        channel: `chat:${room}`
      }));
    };

    ws.onmessage = (e) => {
      const msg = JSON.parse(e.data);
      if (msg.action === 'message') {
        setMessages(prev => [...prev, msg.data]);
      }
    };

    wsRef.current = ws;
    return () => ws.close();
  }, [room]);

  const send = async () => {
    await fetch('/api/chat/send', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ room, user: 'Me', text: input })
    });
    setInput('');
  };

  return (
    <div>
      <div className="messages">
        {messages.map((m, i) => (
          <div key={i}><strong>{m.user}:</strong> {m.text}</div>
        ))}
      </div>
      <input value={input} onChange={e => setInput(e.target.value)} />
      <button onClick={send}>Send</button>
    </div>
  );
}

6. Advanced features

Presence (who is online)

// In the browser — join the room
ws.send(JSON.stringify({
  action: 'presence.enter',
  channel: 'chat:general',
  data: { name: 'Alice', avatar: '/alice.png' }
}));

// Leave the room
ws.send(JSON.stringify({
  action: 'presence.leave',
  channel: 'chat:general'
}));

Message history

// Fetch the last 50 messages from a channel
ws.send(JSON.stringify({
  action: 'history',
  channel: 'chat:general',
  limit: 50
}));

Wildcards (subscribe to multiple channels)

// Receive ALL notifications — any sub-channel
ws.send(JSON.stringify({
  action: 'subscribe',
  channel: 'notifications:*'
}));

// Receives: notifications:orders, notifications:alerts, notifications:system, etc.

7. Security

wsocket.io provides multiple layers of security:

  • JWT Tokens — Token-based authentication with custom claims
  • API Keys with granular permissions — read-only, write-only, admin
  • Rate Limiting — Configurable per app
  • E2E Encryption — End-to-end encryption (Enterprise plan)
// Example with JWT token in the browser
const ws = new WebSocket('wss://node00.wsocket.online/?token=eyJhbGciOi...');

8. Available SDKs

wsocket.io offers SDKs for 16 languages. All publishers work the same way — connect, publish, done:

LanguageInstallRepository
Node.js / JSnpm i @wsocket-io/sdksdk-js
Pythonpip install wsocket-iosdk-python
Gogo get github.com/wsocket-io/sdk-gosdk-go
C# / .NETdotnet add WSocket.IOsdk-csharp
Javaio.wsocket:sdksdk-java
Kotlinio.wsocket:sdk-kotlinsdk-kotlin
Rustcargo add wsocket-iosdk-rust
PHPcomposer require wsocket-io/sdksdk-php
Rubygem install wsocket-iosdk-ruby
SwiftSwift Package Managersdk-swift
Dartdart pub add wsocket_iosdk-dart
Elixir{:wsocket_io, "~> 1.0"}sdk-elixir
CHeader-onlysdk-c
C++Header-onlysdk-cpp
PascalUnit includesdk-pascal

9. Pricing

PlanPriceConnectionsMessages/day
FreeFree10010K
Pro$49/mo10K1M
EnterpriseCustomUnlimitedUnlimited

The Free plan is permanent — no credit card, no 14-day trial. Perfect for development, side projects and MVPs.


Conclusion

wsocket.io drastically simplifies implementing realtime features. Instead of maintaining your own WebSocket infrastructure (Redis, load balancing, reconnection, scaling), you:

  1. Install the SDK (npm i @wsocket-io/sdk)
  2. Connect with API key (1 line)
  3. Publish events from any backend (channel.publish())
  4. Receive in the browser (ws.onmessage)

Everything managed — scaling, reconnection, history, presence, push.

Links: