@gowhiteleaf/socketly-client-sdk
v1.2.0
Published
Official JavaScript/TypeScript client SDK for Socketly - Real-time socket server
Maintainers
Readme
@socketly/client-sdk
Official JavaScript/TypeScript client SDK for Socketly - A production-ready, multi-tenant socket server.
📚 Documentation
📖 Complete documentation: socketly.co/developers
- Full Developer Guide - Integration guides, examples, and best practices
- API Reference - Complete method and event documentation
- React Integration - Hooks, patterns, and examples
- Next.js Integration - App Router setup and SSR
- Get Your API Key - Create a workspace and start building
🚀 Features
- ✅ Type-Safe: Full TypeScript support
- ✅ Framework Agnostic: Works with React, Next.js, Vue, vanilla JS
- ✅ Real-time Communication: Built on Socket.IO
- ✅ Channel Support: Join/leave channels dynamically
- ✅ User Presence: Track online/offline users
- ✅ Auto-Reconnection: Configurable reconnection strategy
- ✅ Event-Driven: Simple event-based API
📦 Installation
npm install @gowhiteleaf/socketly-client-sdk socket.io-clientyarn add @socketly/client-sdk socket.io-clientpnpm add @socketly/client-sdk socket.io-client🔧 Quick Start
Basic Usage
import { GlobalSocketClient } from '@gowhiteleaf/socketly-client-sdk';
// Initialize the client
const socketClient = new GlobalSocketClient({
appKey: 'your-app-key',
userId: 'user-123',
debug: true, // Enable console logs
});
// Listen for connection
socketClient.on('connect', (data) => {
console.log('Connected!', data);
});
// Join a channel
socketClient.joinChannel('chat-room');
// Listen for channel messages
socketClient.on('message', (data) => {
console.log('New message:', data);
});
// Send a message to channel
socketClient.sendToChannel('chat-room', 'message', {
text: 'Hello, world!',
timestamp: Date.now(),
});📚 Framework-Specific Guides
React
For complete React integration guide with advanced hooks and patterns:
Includes:
- Custom hooks (
useSocketly,useChannel,usePresence,useEvent) - Context provider pattern
- Real-time notifications
- Live activity feeds
- Collaborative editing
- Testing strategies
- Best practices
Quick example:
import { useSocketly } from './hooks/useSocketly';
function App() {
const { client, isConnected } = useSocketly({
appKey: 'your-app-key',
userId: 'user-123',
});
// Use client and isConnected...
}Next.js
For complete Next.js 13+ integration guide with App Router:
Includes:
- Socket context provider
- Server components integration
- Real-time chat example
- Notification system
- User presence tracking
- Server-side event emission
- API route examples
- Troubleshooting guide
Quick example:
'use client';
import { useSocket } from '@/lib/socket-context';
export default function Page() {
const { client, isConnected } = useSocket();
// Use client for real-time features...
return <div>Real-time App</div>;
}📚 API Reference
Constructor Options
interface SocketClientConfig {
appKey: string; // Your application key
userId?: string; // User identifier
metadata?: Record<string, any>; // Custom user metadata
autoConnect?: boolean; // Auto-connect on init (default: true)
reconnection?: boolean; // Enable auto-reconnection (default: true)
reconnectionAttempts?: number; // Max reconnection attempts (default: 5)
reconnectionDelay?: number; // Delay between reconnections (default: 1000ms)
debug?: boolean; // Enable debug logs (default: false)
}Methods
connect(): void
Manually connect to the socket server.
client.connect();disconnect(): void
Disconnect from the socket server.
client.disconnect();joinChannel(channelName: string): void
Join a specific channel.
client.joinChannel('notifications');leaveChannel(channelName: string): void
Leave a channel.
client.leaveChannel('notifications');sendToChannel(channelName: string, event: string, payload: any): void
Send a message to a channel.
client.sendToChannel('chat-room', 'message', {
text: 'Hello!',
userId: 'user-123',
});on(event: string, callback: Function): void
Listen for events.
client.on('message', (data) => {
console.log('Received:', data);
});off(event: string, callback?: Function): void
Remove event listener.
client.off('message');ping(): void
Send a ping to the server.
client.ping();getConnectionStatus(): object
Get current connection status.
const status = client.getConnectionStatus();
// { connected: true, socketId: 'xyz', userId: 'user-123' }getJoinedChannels(): string[]
Get list of joined channels.
const channels = client.getJoinedChannels();
// ['chat-room', 'notifications']updateMetadata(metadata: Record<string, any>): void
Update user metadata (requires reconnection).
client.updateMetadata({
status: 'busy',
lastSeen: Date.now(),
});Events
Built-in Events
connect- Connected to serverdisconnect- Disconnected from servererror- Connection errorchannel:joined- Successfully joined a channelchannel:left- Left a channelchannel:member-joined- A user joined the channelchannel:member-left- A user left the channelchannel:error- Channel operation erroruser:online- A user came onlineuser:offline- A user went offlinepong- Response to ping
Custom Events
You can listen for any custom event emitted by the server:
client.on('notification', (data) => {
console.log('New notification:', data);
});
client.on('typing', (data) => {
console.log(`${data.userId} is typing...`);
});🔐 Environment Variables
Create a .env.local file in your Next.js app:
NEXT_PUBLIC_SOCKET_URL=http://localhost:5005
NEXT_PUBLIC_APP_KEY=your-app-key-hereThen use them in your code:
const client = new GlobalSocketClient({
appKey: process.env.NEXT_PUBLIC_APP_KEY!,
userId: session.user.id,
});🎯 Use Cases
Real-time Chat
// Join chat room
client.joinChannel('room-123');
// Send message
client.sendToChannel('room-123', 'message', {
text: 'Hello everyone!',
sender: 'John',
});
// Listen for messages
client.on('message', (data) => {
displayMessage(data.payload);
});Live Notifications
// Join user-specific notification channel
client.joinChannel(`notifications:${userId}`);
// Listen for notifications
client.on('notification', (data) => {
showToast(data.payload.message);
});User Presence
// Track online users
client.on('user:online', (data) => {
updateUserStatus(data.userId, 'online');
});
client.on('user:offline', (data) => {
updateUserStatus(data.userId, 'offline');
});Typing Indicators
// Send typing event
const handleTyping = () => {
client.sendToChannel('chat-room', 'typing', {
userId: currentUser.id,
});
};
// Listen for typing
client.on('typing', (data) => {
showTypingIndicator(data.userId);
});🛠️ Development
Build
npm run buildWatch Mode
npm run devType Check
npm run typecheck📝 TypeScript Support
The SDK is written in TypeScript and includes full type definitions:
import {
GlobalSocketClient,
SocketClientConfig,
ChannelEventData,
UserOnlineEventData,
UserOfflineEventData,
} from '@socketly/client-sdk';🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
📄 License
MIT © Socketly
🔗 Links
💬 Support
Need help? Open an issue or reach out:
- GitHub Issues: Report a bug
- Email: [email protected]
