typed-socket-client
v1.0.1
Published
A fully typed [Socket.IO](https://socket.io/) client wrapper with:
Readme
typed-socket-client
A fully typed Socket.IO client wrapper with:
- 🔒 Type-safe events — strongly typed server→client and client→server payloads
- 🔁 Auto reconnect — built on Socket.IO's reconnection, fully configurable
- 📦 Offline queue —
emitwhile disconnected is buffered and flushed on reconnect - 📡 Status tracking — subscribe to connection lifecycle changes
- 🚨 Error handling — global handler plus per-event error channels
Install
pnpm add typed-socket-client
# or
npm install typed-socket-client
# or
yarn add typed-socket-clientsocket.io-client is a runtime dependency and is installed automatically.
Quick start
Declare two maps describing your events: one for messages the server emits to the client (ServerEvents) and one for messages the client emits to the server (ClientEvents).
import { createSocketClient } from 'typed-socket-client'
// Events the server sends to the client
interface ServerEvents {
'message': { id: string; text: string }
'user:joined': { userId: string }
}
// Events the client sends to the server
interface ClientEvents {
'message:send': { text: string }
'typing': { isTyping: boolean }
}
const client = createSocketClient<ServerEvents, ClientEvents>({
url: 'https://api.example.com',
reconnect: true,
retries: 5,
maxQueue: 50,
events: {
message: (data) => {
// data is typed as { id: string; text: string }
console.log(data.text)
},
},
onError: (err) => console.error('Socket error', err),
})
client.connect()
// Fully typed emit — payload must match ClientEvents['message:send']
client.emit('message:send', { text: 'Hello!' })API
createSocketClient<S, C>(options)
Creates a typed client. The generics are:
| Generic | Description |
| ------- | ----------- |
| S | Map of server→client events ({ eventName: payloadType }) |
| C | Map of client→server events ({ eventName: payloadType }) |
Options
| Option | Type | Default | Description |
| ------ | ---- | ------- | ----------- |
| url | string | — | Required. The Socket.IO server URL. |
| reconnect | boolean | true | Enable automatic reconnection. |
| retries | number | 5 | Maximum reconnection attempts. |
| maxQueue | number | 50 | Max number of messages buffered while offline. Extra messages are dropped. |
| events | object | — | Map of server events to handlers (see Event handlers). |
| onError | (err: unknown) => void | — | Called on connect_error and on any per-event error. |
| onConnectionError | () => void | — | Called on connect_error. |
| onReconnectFailed | () => void | — | Called when all reconnection attempts are exhausted. |
Note: the socket is created with
autoConnect: false. You must callconnect()to open the connection.
Event handlers
Each entry in events can be either a plain callback or an object with extra control:
events: {
// Plain callback
message: (data) => console.log(data),
// Object form with error handling and one-time listening
'user:joined': {
cb: (data) => console.log('joined', data.userId),
error: (err) => console.error(err), // listens to 'user:joined:error'
once: true, // remove after first invocation
},
}When you provide the object form, an error listener is automatically registered on the <event>:error channel. Both error (per-event) and onError (global) are invoked.
Returned client
| Method | Signature | Description |
| ------ | --------- | ----------- |
| connect | () => void | Opens the connection and sets status to connecting. |
| disconnect | () => void | Closes the connection, removes all listeners, and clears the offline queue. |
| emit | (event, payload, cb?) => void | Typed emit. If not connected, the message is queued (up to maxQueue) and flushed on reconnect. |
| on | (event, cb) => () => void | Subscribe to a server event at runtime. Returns an unsubscribe function. |
| onStatusChange | (cb) => () => void | Subscribe to status changes (called immediately with current status). Returns an unsubscribe function. |
| getStatus | () => SocketStatus | Returns the current connection status. |
| getSocketId | () => string \| null | Returns the current socket id, or null if not connected. |
Status
SocketStatus is one of:
'idle' | 'connecting' | 'connected' | 'disconnected' | 'reconnecting' | 'connect_error'const unsubscribe = client.onStatusChange((status) => {
console.log('Connection status:', status)
})
// Later
unsubscribe()Offline queue
When you call emit while the client is not connected, the message is pushed into an in-memory queue instead of being lost. Once the connection is (re)established, the queue is flushed in FIFO order. If the queue is already at maxQueue, further messages are silently dropped.
client.emit('message:send', { text: 'Sent while offline' }) // queued
// ...connection restored...
// queued message is automatically emittedRuntime subscriptions
Besides the events option, you can subscribe to server events after creation:
const off = client.on('message', (data) => {
console.log(data.text)
})
// Stop listening
off()License
ISC
