npm package: @gowhiteleaf/socketly-client-sdk
Description: Official JavaScript/TypeScript client SDK for Socketly - Real-time socket server
Author: Jaspreet Singh
Latest version: 1.2.0

# @socketly/client-sdk

Official JavaScript/TypeScript client SDK for **Socketly** - A production-ready, multi-tenant socket server.

## 📚 Documentation

**📖 Complete documentation: [socketly.co/developers](https://socketly.co/developers)**

- [Full Developer Guide](https://socketly.co/developers) - Integration guides, examples, and best practices
- [API Reference](https://socketly.co/developers#api) - Complete method and event documentation
- [React Integration](https://socketly.co/developers#react) - Hooks, patterns, and examples
- [Next.js Integration](https://socketly.co/developers#nextjs) - App Router setup and SSR
- [Get Your API Key](https://socketly.co/dashboard) - 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

```bash
npm install @gowhiteleaf/socketly-client-sdk socket.io-client
```

```bash
yarn add @socketly/client-sdk socket.io-client
```

```bash
pnpm add @socketly/client-sdk socket.io-client
```

## 🔧 Quick Start

### Basic Usage

```typescript
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:

**👉 [React Integration Guide](./examples/react-example.mdx)**

Includes:

- Custom hooks (`useSocketly`, `useChannel`, `usePresence`, `useEvent`)
- Context provider pattern
- Real-time notifications
- Live activity feeds
- Collaborative editing
- Testing strategies
- Best practices

Quick example:

```tsx
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:

**👉 [Next.js Integration Guide](./examples/nextjs-example.mdx)**

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:

```tsx
'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

```typescript
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.

```typescript
client.connect();
```

#### `disconnect(): void`

Disconnect from the socket server.

```typescript
client.disconnect();
```

#### `joinChannel(channelName: string): void`

Join a specific channel.

```typescript
client.joinChannel('notifications');
```

#### `leaveChannel(channelName: string): void`

Leave a channel.

```typescript
client.leaveChannel('notifications');
```

#### `sendToChannel(channelName: string, event: string, payload: any): void`

Send a message to a channel.

```typescript
client.sendToChannel('chat-room', 'message', {
  text: 'Hello!',
  userId: 'user-123',
});
```

#### `on(event: string, callback: Function): void`

Listen for events.

```typescript
client.on('message', (data) => {
  console.log('Received:', data);
});
```

#### `off(event: string, callback?: Function): void`

Remove event listener.

```typescript
client.off('message');
```

#### `ping(): void`

Send a ping to the server.

```typescript
client.ping();
```

#### `getConnectionStatus(): object`

Get current connection status.

```typescript
const status = client.getConnectionStatus();
// { connected: true, socketId: 'xyz', userId: 'user-123' }
```

#### `getJoinedChannels(): string[]`

Get list of joined channels.

```typescript
const channels = client.getJoinedChannels();
// ['chat-room', 'notifications']
```

#### `updateMetadata(metadata: Record<string, any>): void`

Update user metadata (requires reconnection).

```typescript
client.updateMetadata({
  status: 'busy',
  lastSeen: Date.now(),
});
```

### Events

#### Built-in Events

- `connect` - Connected to server
- `disconnect` - Disconnected from server
- `error` - Connection error
- `channel:joined` - Successfully joined a channel
- `channel:left` - Left a channel
- `channel:member-joined` - A user joined the channel
- `channel:member-left` - A user left the channel
- `channel:error` - Channel operation error
- `user:online` - A user came online
- `user:offline` - A user went offline
- `pong` - Response to ping

#### Custom Events

You can listen for any custom event emitted by the server:

```typescript
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:

```env
NEXT_PUBLIC_SOCKET_URL=http://localhost:5005
NEXT_PUBLIC_APP_KEY=your-app-key-here
```

Then use them in your code:

```typescript
const client = new GlobalSocketClient({
  appKey: process.env.NEXT_PUBLIC_APP_KEY!,
  userId: session.user.id,
});
```

## 🎯 Use Cases

### Real-time Chat

```typescript
// 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

```typescript
// Join user-specific notification channel
client.joinChannel(`notifications:${userId}`);

// Listen for notifications
client.on('notification', (data) => {
  showToast(data.payload.message);
});
```

### User Presence

```typescript
// Track online users
client.on('user:online', (data) => {
  updateUserStatus(data.userId, 'online');
});

client.on('user:offline', (data) => {
  updateUserStatus(data.userId, 'offline');
});
```

### Typing Indicators

```typescript
// 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

```bash
npm run build
```

### Watch Mode

```bash
npm run dev
```

### Type Check

```bash
npm run typecheck
```

## 📝 TypeScript Support

The SDK is written in TypeScript and includes full type definitions:

```typescript
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

- [Documentation](https://github.com/yourusername/socketly-client-sdk)
- [Report Issues](https://github.com/yourusername/socketly-client-sdk/issues)
- [Server Repository](https://github.com/yourusername/socketly)

## 💬 Support

Need help? Open an issue or reach out:

- GitHub Issues: [Report a bug](https://github.com/yourusername/socketly-client-sdk/issues)
- Email: support@socketly.dev