Back to Documentation

Node.js SDK Examples

Real-world examples showing how to use the OddSockets Node.js SDK in server-side applications

Download Example Code
Basic Usage
Available
Simple example showing how to connect, subscribe to a channel, and publish messages using the core SDK functionality in Node.js.
const OddSockets = require('@oddsocketsai/nodejs-sdk');

const client = new OddSockets({
  apiKey: 'ak_live_1234567890abcdef',
  userId: 'server-user-123'
});

const channel = client.channel('my-channel');

// Subscribe to messages
await channel.subscribe((message) => {
  console.log('Received:', message);
});

// Publish a message
await channel.publish({
  text: 'Hello from Node.js server!',
  timestamp: new Date().toISOString()
});
PubNub Migration
Available
Drop-in replacement example showing how to migrate from PubNub to OddSockets with minimal code changes in Node.js applications.
// Replace PubNub with OddSockets
const { PubNubCompat } = require('@oddsocketsai/nodejs-sdk');

const pubnub = new PubNubCompat({
  publishKey: 'ak_live_1234567890abcdef',
  subscribeKey: 'ak_live_1234567890abcdef',
  userId: 'server123'
});

// Same API as PubNub!
pubnub.addListener({
  message: function(messageEvent) {
    console.log('Message:', messageEvent.message);
  }
});

pubnub.subscribe({
  channels: ['server-channel']
});
Express.js Integration
Available
Complete example showing how to integrate OddSockets with Express.js for building real-time APIs and webhooks.
const express = require('express');
const OddSockets = require('@oddsocketsai/nodejs-sdk');

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

// Initialize OddSockets
const client = new OddSockets({
  apiKey: 'ak_live_1234567890abcdef'
});

// API endpoint to send messages
app.post('/api/send-message', async (req, res) => {
  try {
    const { channel, message } = req.body;
    const oddSocketsChannel = client.channel(channel);
    
    const result = await oddSocketsChannel.publish(message);
    res.json({ success: true, result });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.listen(3000);
Production Deployment
Available
Production-ready configuration with error handling, graceful shutdown, and environment variable management.
const OddSockets = require('@oddsocketsai/nodejs-sdk');

const client = new OddSockets({
  apiKey: process.env.ODDSOCKETS_API_KEY,
  userId: process.env.ODDSOCKETS_USER_ID || 'server-prod',
  options: {
    transports: ['websocket'],      // WebSocket only
    timeout: 10000,                 // 10 second timeout
    reconnection: true,             // Enable auto-reconnection
    reconnectionAttempts: 10,       // More attempts in production
    maxReconnectionAttempts: 50     // Higher limit for production
  }
});

// Production error handling
client.on('error', (error) => {
  console.error('OddSockets error:', error);
});

// Graceful shutdown
process.on('SIGTERM', () => {
  console.log('Shutting down gracefully...');
  client.disconnect();
  process.exit(0);
});
Bulk Operations
Available
Efficient bulk message publishing for high-throughput applications and batch processing scenarios.
const OddSockets = require('@oddsocketsai/nodejs-sdk');

const client = new OddSockets({
  apiKey: 'ak_live_1234567890abcdef'
});

// Publish multiple messages at once
const results = await client.publishBulk([
  { channel: 'notifications', message: 'User logged in' },
  { channel: 'analytics', message: { event: 'page_view' } },
  { channel: 'alerts', message: 'System status: OK' }
]);

results.forEach((result, index) => {
  if (result.success) {
    console.log(`Message ${index + 1} published successfully`);
  } else {
    console.error(`Message ${index + 1} failed:`, result.error);
  }
});
Docker Deployment
Available
Complete Docker setup with multi-stage builds, health checks, and container orchestration for scalable deployments.
FROM node:18-alpine

WORKDIR /app

# Copy package files
COPY package*.json ./

# Install dependencies
RUN npm ci --only=production

# Copy application code
COPY . .

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s \
  CMD node healthcheck.js || exit 1

# Expose port
EXPOSE 3000

# Start application
CMD ["node", "server.js"]