JOIN MY SPONSORS

API Reference

All methods are chainable and return the IttySocket instance.

connect(channel: string, options?: IttySocketOptions): IttySocket

Connect to an itty-sockets channel. Returns an IttySocket with the full itty protocol (IttyProtocoluid, alias, date on all events).

connect.js
import { connect } from 'itty-sockets'

const channel = connect('my-channel', {
  as: 'Kevin',
  announce: true,
  echo: true,
})
OptionTypeDescription
as / aliasstringDisplay name for this connection
announcetrueBroadcast identity in join/leave events
echotrueReceive your own messages back
joinKeystringKey required to join a protected channel
sendKeystringKey required to send on a protected channel

See IttySocketOptions for the full type.

connect(url: string, queryParams?: object): IttySocket

Connect directly to any WebSocket server by passing a ws:// or wss:// URL. The second argument is serialized as query parameters. itty protocol features (uid, alias, join/leave events) are not available in this mode.

raw.js
import { connect } from 'itty-sockets'

const ws = connect('wss://my-server.com/ws', { token: 'abc' })
// connects to wss://my-server.com/ws?token=abc

.on(type: string, listener: Function): IttySocket

Register a listener for an event type. The listener receives an event object whose shape depends on the type. See Receiving Messages for full usage.

.on('message', listener)

Fires for any incoming message that doesn't have a type field. The event includes the raw message payload plus sender details. See MessageEvent<T>.

channel.on('message', ({ message, uid, alias, date }) => {
  console.log(`${alias}: ${message}`)
})

.on('join', listener)

Fires when a user connects to the channel. Always includes users (total count). uid and alias are only present when the joiner connected with announce: true. See JoinEvent.

channel.on('join', ({ uid, alias, users, date }) => {
  console.log(`${alias} joined (${users} online)`)
})

.on('leave', listener)

Fires when a user disconnects. Same shape as join. See LeaveEvent.

channel.on('leave', ({ uid, alias, users, date }) => {
  console.log(`${alias} left (${users} online)`)
})

.on('error', listener)

Fires on server errors — rate limit exceeded, send permission denied, etc. See ErrorEvent.

channel.on('error', ({ message, date }) => {
  console.error('server error:', message)
})

.on(customType, listener)

Messages with a type field are routed to listeners matching that type. The message properties are spread to the top level of the event for convenience. See Type Routing.

// messages with { type: 'chat' } are routed here
channel.on('chat', ({ text, uid, alias }) => {
  console.log(`${alias}: ${text}`)
})

.on('*', listener)

Wildcard — fires for every event: messages, joins, leaves, errors, and custom types. Useful for logging or debugging.

// fires for every event — messages, joins, leaves, errors, custom types
channel.on('*', (event) => {
  console.log(event.type, event)
})

.on('open', listener) / .on('close', listener)

Lifecycle events for the underlying WebSocket connection. No event payload — just a notification.

channel
  .on('open', () => console.log('connected'))
  .on('close', () => console.log('disconnected'))

.on(filterFn: Function, listener: Function): IttySocket

Pass a filter function as the first argument. The listener only fires when the function returns true. See Filter Functions.

// listener fires only when the filter function returns true
channel.on(
  (event) => event.uid === 'abc123',
  (event) => console.log('from abc123:', event.message)
)

.send(message: T, uid?: string): IttySocket

Send a JSON-serializable message. Broadcast to all users on the channel, or send a direct message to a specific user by passing their uid. With an event map, sends are type-checked.

channel.send('hello')                        // string
channel.send({ type: 'chat', text: 'hey' })  // typed object
channel.send({ x: 10, y: 20 })               // any JSON value
channel.send({ text: 'psst' }, uid)          // DM to user

.push(message: T, uid?: string): IttySocket

Send a message and immediately disconnect. Same signature as .send(). Useful for fire-and-forget patterns.

// send a message and immediately disconnect
channel.push({ type: 'alert', text: 'server restarting' })

.open(): IttySocket

Connect or reconnect. Creates a new underlying WebSocket internally, but the IttySocket instance stays the same — all listeners and options are preserved. Safe to call at any time; no-op if already connected. See Reconnecting.

// reconnect every second if disconnected
setInterval(channel.open, 1000)

.close(): IttySocket

Close the WebSocket connection. The instance can be reopened later with .open().

.remove(type: string, listener: Function): IttySocket

Unregister a specific listener. You must pass the same function reference that was passed to .on(). See Removing Listeners.

const logger = (event) => console.log(event)

channel.on('message', logger)
channel.remove('message', logger)

Next: Type Referenceevery type, interface, and event shape in one place.