OddSockets Node.js SDK
Official Node.js SDK for OddSockets real-time messaging platform
Overview & Features
The OddSockets Node.js SDK provides a powerful, easy-to-use interface for real-time messaging in server-side Node.js applications.
Node.js Optimized
Built specifically for Node.js with CommonJS modules and server-side optimizations.
JSDoc Ready
Comprehensive JSDoc documentation with IntelliSense support in all editors.
PubNub Compatible
Drop-in replacement for PubNub with migration utilities included.
High Performance
Optimized for low latency with efficient WebSocket connections and smart routing.
Cost Effective
No per-message pricing, industry-standard 32KB message limits, transparent pricing.
Automatic Failover
Built-in redundancy and intelligent error handling for 99.9% uptime.
Installation
npm install @oddsocketsai/nodejs-sdk
yarn add @oddsocketsai/nodejs-sdk
pnpm add @oddsocketsai/nodejs-sdk
Quick Start
Basic Usage
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
const { PubNubCompat } = require('@oddsocketsai/nodejs-sdk');
// Drop-in replacement for PubNub
const pubnub = new PubNubCompat({
publishKey: 'ak_live_1234567890abcdef',
subscribeKey: 'ak_live_1234567890abcdef',
userId: 'server123'
});
pubnub.addListener({
message: function(messageEvent) {
console.log('Message:', messageEvent.message);
}
});
pubnub.subscribe({
channels: ['server-channel']
});
Express.js Integration
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, () => {
console.log('Server running on port 3000');
});
Configuration
Client Options
const client = new OddSockets({
apiKey: 'your-api-key', // Required: Your OddSockets API key
userId: 'server-id', // Optional: Server identifier
autoConnect: true, // Optional: Auto-connect on creation
options: { // Optional: Socket.IO options
transports: ['websocket'], // Force WebSocket only
timeout: 15000, // Connection timeout
reconnection: true, // Enable reconnection
reconnectionAttempts: 5, // Max reconnection attempts
maxReconnectionAttempts: 10 // Max total attempts
}
});
Channel Options
// Subscribe with options
await channel.subscribe(callback, {
enablePresence: true, // Enable presence tracking
retainHistory: true, // Retain message history
maxHistory: 100 // Maximum messages to retain
});
// Publish with options
await channel.publish(message, {
ttl: 3600, // Time to live (seconds)
metadata: { priority: 'high' }, // Additional metadata
storeInHistory: true // Store in message history
});
Examples
Explore comprehensive examples demonstrating the OddSockets Node.js SDK in action:
Performance & Compatibility
OddSockets Node.js SDK delivers superior performance with broad Node.js compatibility:
Node.js Support
- Node.js 14+ (LTS)
- Node.js 16+ (Recommended)
- Node.js 18+ (Latest)
- Node.js 20+ (Current)
Module Support
- CommonJS (require)
- ES2020+ features
- JSDoc documentation
- IntelliSense support
Deployment & Production
The OddSockets Node.js SDK is optimized for production deployments with various hosting platforms and frameworks:
Docker Deployment
FROM node:18-alpine
WORKDIR /app
# Copy package files
COPY package*.json ./
# Install dependencies
RUN npm ci --only=production
# Copy application code
COPY . .
# Expose port
EXPOSE 3000
# Start application
CMD ["node", "server.js"]
Environment Variables
# .env file
ODDSOCKETS_API_KEY=ak_live_1234567890abcdef
ODDSOCKETS_USER_ID=server-production
NODE_ENV=production
PORT=3000
Production Configuration
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 for production
timeout: 10000, // 10 second timeout
reconnection: true, // Enable auto-reconnection
reconnectionAttempts: 10, // More attempts in production
reconnectionDelay: 1000, // Start with 1 second delay
maxReconnectionAttempts: 50 // Higher limit for production
}
});
// Production error handling
client.on('error', (error) => {
console.error('OddSockets error:', error);
// Log to your monitoring service
});
client.on('reconnecting', (attempt) => {
console.log(`Reconnecting to OddSockets... attempt ${attempt.attempt}`);
});
// Graceful shutdown
process.on('SIGTERM', () => {
console.log('Shutting down gracefully...');
client.disconnect();
process.exit(0);
});
Hosting Platforms
AWS/Azure/GCP
Deploy on major cloud platforms with auto-scaling and load balancing support.
Docker/Kubernetes
Container-ready with health checks and graceful shutdown handling.
Heroku/Railway
Platform-as-a-Service ready with automatic environment detection.
Vercel/Netlify
Serverless function support for event-driven architectures.