Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/strophe/strophejs/llms.txt

Use this file to discover all available pages before exploring further.

The Connection class is the central component of Strophe.js. It manages a BOSH or WebSocket connection to an XMPP server, handles SASL authentication, dispatches incoming stanzas to registered handlers, and exposes methods for sending stanzas and controlling connection lifecycle. All client code interacts with XMPP through a Connection instance.

Constructor

new Strophe.Connection(service: string, options?: ConnectionOptions)
Creates and initializes a new Connection object. The transport protocol is selected automatically based on the service URL: URLs beginning with ws:// or wss:// use WebSocket; URLs beginning with http://, https://, or a bare path use BOSH. Passing a worker option will use a shared WorkerWebSocket transport instead.
service
string
required
The BOSH endpoint URL or WebSocket URL for the XMPP server. You can also pass a relative path (e.g. "/http-bind/" or "/xmpp-websocket/") and the current page’s protocol and host will be used.
options
ConnectionOptions
Optional configuration object. See the ConnectionOptions reference for the full list of available fields.
// BOSH connection
const conn = new Strophe.Connection("https://xmpp.example.com/http-bind/");

// WebSocket connection
const conn = new Strophe.Connection("wss://xmpp.example.com/xmpp-websocket/");

// Relative path (protocol resolved from the current page)
const conn = new Strophe.Connection("/http-bind/", { keepalive: true });

Connection Methods

connect

connect(
  jid: string,
  pass: string | Password,
  callback?: ConnectCallback,
  wait?: number,
  hold?: number,
  route?: string,
  authcid?: string,
  disconnection_timeout?: number
): void
Starts the connection process. As authentication proceeds, the callback is invoked multiple times with a Strophe.Status code and an optional error condition string. User-registered handlers become active only after authentication succeeds.
jid
string
required
The user’s JID. May be a bare JID (user@domain) or a full JID (user@domain/resource). Omitting the node part triggers SASL OAUTHBEARER or SASL ANONYMOUS authentication.
pass
string | Password
required
The user’s plaintext password, or a pre-computed SCRAM key object with the shape { name, ck, sk, iter, salt }.
callback
(status: number, condition: string | null, elem?: Element) => void
Invoked on every connection status change. status is one of the Strophe.Status constants. condition carries an RFC 3920 error condition string on failure, or null on success. elem is the triggering XML element when available.
wait
number
BOSH only. The HTTPBIND wait attribute in seconds — how long the server holds an open request before returning an empty response. Defaults to 60.
hold
number
BOSH only. The HTTPBIND hold attribute — how many simultaneous requests the server keeps open. Almost always 1 (the default).
route
string
BOSH only. An optional route attribute forwarded verbatim to the BOSH connection manager.
authcid
string
An alternative authentication identity (username) used for impersonation or SASL EXTERNAL. When omitted, the node part of jid is used.
disconnection_timeout
number
Milliseconds to wait for a clean disconnect before forcing _doDisconnect. Defaults to 3000.
const conn = new Strophe.Connection("https://xmpp.example.com/http-bind/");

conn.connect("alice@example.com", "s3cr3t", (status, condition) => {
  if (status === Strophe.Status.CONNECTED) {
    console.log("Connected!");
  } else if (status === Strophe.Status.CONNFAIL) {
    console.error("Connection failed:", condition);
  } else if (status === Strophe.Status.DISCONNECTED) {
    console.log("Disconnected.");
  }
});

attach

attach(
  jid: string | (() => void),
  sid?: string,
  rid?: number,
  callback?: ConnectCallback,
  wait?: number,
  hold?: number,
  wind?: number
): void
Attaches to an existing, externally-created BOSH session. This is used when a server-side component (e.g. a web application) pre-authenticates the user and hands off the BOSH session tokens. Only available for BOSH connections. When using a WorkerWebsocket transport, pass a function instead of a JID to hand off the worker connection. Throws a SessionError for unsupported transports.
jid
string | (() => void)
required
For BOSH connections, the full JID already bound by the session (e.g. alice@example.com/resource). For WorkerWebsocket connections, a callback function used to hand off the worker.
sid
string
The BOSH session ID (sid) returned by the session manager.
rid
number
The next request ID (rid) to use. This is the value the BOSH connection manager expects on the next request.
callback
(status: number, condition: string | null, elem?: Element) => void
The connect callback, same signature as for connect().
wait
number
BOSH wait value in seconds. Defaults to 60.
hold
number
BOSH hold value. Defaults to 1.
wind
number
BOSH window value — the allowed range of valid request IDs. Defaults to 5.
// Tokens typically come from a server-side auth endpoint
const { jid, sid, rid } = await fetch("/api/xmpp-session").then(r => r.json());

const conn = new Strophe.Connection("https://xmpp.example.com/http-bind/");
conn.attach(jid, sid, rid, onConnect);

restore

restore(
  jid?: string,
  callback?: ConnectCallback,
  wait?: number,
  hold?: number,
  wind?: number
): void
Attempts to resume a BOSH session that was cached in sessionStorage by a previous page load. Requires the keepalive: true option to have been set when the original connection was created. Must be called instead of connect() or attach() to resume. Throws a SessionError when the connection is not BOSH or sessionStorage is unavailable.
jid
string
Optional JID hint used to locate the stored session tokens.
callback
(status: number, condition: string | null, elem?: Element) => void
The connect callback, same signature as for connect().
wait
number
BOSH wait value in seconds.
hold
number
BOSH hold value.
wind
number
BOSH window value.
const conn = new Strophe.Connection("/http-bind/", { keepalive: true });

conn.restore("alice@example.com", (status) => {
  if (status === Strophe.Status.CONNECTED) {
    console.log("Session restored!");
  } else if (status === Strophe.Status.CONNFAIL) {
    // No cached session — fall back to a normal connect
    conn.connect("alice@example.com", password, onConnect);
  }
});

disconnect

disconnect(reason?: string): void
Initiates a graceful disconnection. When connected, Strophe sends an <unavailable> presence stanza and a BOSH terminate body (or WebSocket close frame), then waits up to disconnection_timeout milliseconds before forcing the connection closed. When called before the connection is established, it aborts all pending requests immediately.
reason
string
A human-readable string describing why the disconnection occurred. Logged and passed to the connect callback as the condition argument.
conn.disconnect("user initiated logout");

flush

flush(): void
Cancels the pending 100 ms idle timer and immediately sends all queued outgoing stanzas. Use this after a burst of send() calls when you need data to leave the browser right away rather than waiting for the next idle period.
conn.send($msg({ to: "bob@example.com" }).c("body").t("Hello"));
conn.send($msg({ to: "carol@example.com" }).c("body").t("Hi"));
conn.flush(); // both messages sent immediately

pause

pause(): void
Suspends all outgoing requests. While paused, calls to send() queue stanzas locally but nothing is transmitted to the server. Useful for batching many stanzas together before sending.
conn.pause();
// Queue up many stanzas without triggering individual network requests
for (const msg of messages) {
  conn.send(msg);
}
conn.resume(); // All queued stanzas are sent in one or a few requests

resume

resume(): void
Resumes normal operation after a call to pause(), allowing the connection to send all queued stanzas.

bind

bind(): void
Sends an IQ stanza to the server to bind a JID resource for the current session (RFC 6120 §7.5). This is called automatically during authentication unless explicitResourceBinding: true was set in the connection options, in which case the client must call bind() manually after receiving Strophe.Status.BINDREQUIRED.
bind() has no effect if do_bind is false — i.e. the server has not yet advertised the urn:ietf:params:xml:ns:xmpp-bind stream feature.
const conn = new Strophe.Connection("/http-bind/", {
  explicitResourceBinding: true,
});

conn.connect("alice@example.com", password, (status) => {
  if (status === Strophe.Status.BINDREQUIRED) {
    // Set up XEP-0198 Stream Management before binding
    setupStreamManagement(conn);
    conn.bind();
  }
});

send

send(stanza: Element | Builder | (Element | Builder)[]): void
Queues one or more stanzas for transmission. Stanzas are buffered and sent during the next idle period (every ~100 ms) or when flush() is called. Both Builder instances and raw DOM Element objects are accepted.
stanza
Element | Builder | (Element | Builder)[]
required
A single stanza as a DOM Element, a Strophe Builder object, or an array mixing both types.
// Using a Builder (recommended)
conn.send(
  $msg({ to: "bob@example.com", type: "chat" })
    .c("body").t("Hello, Bob!")
);

// Using a raw Element
const msg = document.createElementNS("jabber:client", "message");
msg.setAttribute("to", "bob@example.com");
conn.send(msg);

// Sending an array of stanzas
conn.send([
  $pres().c("show").t("away"),
  $msg({ to: "bob@example.com" }).c("body").t("BRB"),
]);

sendIQ

sendIQ(
  stanza: Element | Builder,
  callback?: (stanza: Element) => void,
  errback?: (stanza: Element | null) => void,
  timeout?: number
): string
Sends an IQ stanza and registers a one-shot response handler. When the server replies with type="result", callback is called with the response element. When the server replies with type="error", or when the optional timeout fires, errback is called (with null on timeout). Returns the id attribute that was used.
stanza
Element | Builder
required
The IQ stanza to send. If no id attribute is present, one is generated automatically via getUniqueId("sendIQ").
callback
(stanza: Element) => void
Called with the <iq type="result"> response element.
errback
(stanza: Element | null) => void
Called with the <iq type="error"> element, or null when a timeout occurs.
timeout
number
Milliseconds to wait for a response before calling errback(null).
returns
string
The id attribute of the sent IQ stanza.
const id = conn.sendIQ(
  $iq({ type: "get" }).c("query", { xmlns: Strophe.NS.ROSTER }),
  (result) => {
    const items = result.querySelectorAll("item");
    items.forEach((item) => console.log(item.getAttribute("jid")));
  },
  (err) => {
    if (err === null) {
      console.error("IQ timed out");
    } else {
      console.error("IQ error:", err);
    }
  },
  5000 // 5-second timeout
);

sendPresence

sendPresence(
  stanza: Element | Builder,
  callback?: (stanza: Element) => void,
  errback?: (stanza: Element | null) => void,
  timeout?: number
): string
Sends a presence stanza and optionally registers a one-shot handler for the response with the same id. Useful when you need to detect a directed presence reply (e.g. leaving a MUC room) or an error response.
stanza
Element | Builder
required
The presence stanza. An id is injected if not present.
callback
(stanza: Element) => void
Called when a non-error response presence with the same id is received.
errback
(stanza: Element | null) => void
Called with an error presence element, or null on timeout.
timeout
number
Milliseconds before errback(null) is called.
returns
string
The id attribute of the sent presence stanza.
// Send initial available presence
conn.sendPresence($pres());

// Leave a MUC room and wait for the server echo
conn.sendPresence(
  $pres({ to: "room@conference.example.com/Nick", type: "unavailable" }),
  () => console.log("Left the room"),
  (err) => console.error("Error leaving room:", err),
  3000
);

Handler Methods

addHandler

addHandler(
  handler: (stanza: Element) => boolean,
  ns: string | null,
  name: string | null,
  type: string | string[] | null,
  id?: string | null,
  from?: string | null,
  options?: HandlerOptions
): Handler
Registers a stanza handler. The handler is invoked for every incoming stanza that matches all supplied non-null filter criteria simultaneously. The handler must return true to remain active, or false to be automatically unregistered after the first match. Save the return value if you need to remove the handler manually with deleteHandler().
User-registered handlers only fire after authentication succeeds. Handlers registered with _addSysHandler() (internal API) fire from the start.
handler
(stanza: Element) => boolean
required
Callback invoked with the matching DOM stanza element. Return true to keep the handler active; return false to remove it.
ns
string | null
required
XML namespace to match against the stanza element or any of its immediate children. Pass null to match any namespace.
name
string | null
required
Stanza tag name to match (e.g. "message", "iq", "presence"). Pass null to match any tag name.
type
string | string[] | null
required
The type attribute value to match. Pass an array to match any of several types. Pass null to match any type.
id
string | null
Stanza id attribute to match exactly. null matches any id.
from
string | null
Stanza from attribute to match. When options.matchBareFromJid is true, comparison uses bare JIDs. null matches any sender.
options
HandlerOptions
returns
Handler
An opaque Handler reference. Pass this to deleteHandler() to unregister.
const handlerRef = conn.addHandler(
  (stanza) => {
    const from = stanza.getAttribute("from");
    const body = stanza.querySelector("body")?.textContent;
    console.log(`Message from ${from}: ${body}`);
    return true; // keep firing
  },
  null,         // any namespace
  "message",    // <message> stanzas only
  "chat"        // type="chat" only
);

addTimedHandler

addTimedHandler(period: number, handler: () => boolean): TimedHandler
Registers a callback that fires repeatedly every period milliseconds for as long as it returns true. Returning false removes the handler. Save the return value to remove the handler early with deleteTimedHandler().
Timed handlers become active only after authentication succeeds.
period
number
required
Interval in milliseconds between invocations.
handler
() => boolean
required
Callback that takes no arguments. Return true to reschedule; return false to remove the handler.
returns
TimedHandler
An opaque TimedHandler reference for use with deleteTimedHandler().
// Send a keepalive presence every 60 seconds
const pingRef = conn.addTimedHandler(60_000, () => {
  conn.send($pres());
  return true; // keep running
});

// Cancel it later
conn.deleteTimedHandler(pingRef);

deleteHandler

deleteHandler(handRef: Handler): void
Unregisters a stanza handler. handRef must be the value returned by addHandler(), not the original callback function. Deletion is deferred to the next idle loop to avoid modifying the handler list during iteration.
handRef
Handler
required
The Handler reference returned by addHandler().
const ref = conn.addHandler(onMessage, null, "message", "chat");
// … later …
conn.deleteHandler(ref);

deleteTimedHandler

deleteTimedHandler(handRef: TimedHandler): void
Unregisters a timed handler. handRef must be the value returned by addTimedHandler(). Deletion is deferred to the next idle loop.
handRef
TimedHandler
required
The TimedHandler reference returned by addTimedHandler().
const ref = conn.addTimedHandler(5000, pollServer);
// … later …
conn.deleteTimedHandler(ref);

Properties

jid
string
The full JID of the connected user, set immediately when connect() is called and updated with the server-assigned resource after resource binding completes.
authzid
string | null
The authorization identity — the bare JID derived from jid at connect time. Used in SASL exchanges to identify who the client is acting on behalf of.
domain
string | null
The XMPP domain extracted from jid (the part between @ and /). Set during connect().
service
string
The service URL passed to the constructor. Reflects the BOSH endpoint or WebSocket URL in use.
connected
boolean
true when the connection to the server is established and authenticated. Set to false during disconnection.
disconnecting
boolean
true while a graceful disconnection is in progress (after disconnect() is called but before the connection is fully closed).
paused
boolean
true after pause() is called, false after resume(). When true, no outgoing data is transmitted.
restored
boolean
true when the connection was established via restore() from a cached BOSH session rather than a fresh connect().
options
ConnectionOptions
The full options object passed to the constructor (or an empty object if none was supplied). You can mutate properties like options.sync at runtime.
maxRetries
number
The maximum number of reconnection attempts before the connection is abandoned and Strophe.Status.CONNFAIL is fired. Defaults to 5. You can increase this on an existing connection instance before calling connect().

Event Hooks

These methods exist as no-ops on Connection.prototype. Override them directly on a connection instance to intercept raw and structured traffic without registering a handler.

xmlInput

xmlInput(elem: Node | MessageEvent): void
Called with each XML element received from the server before stanza handlers run. Override this to log or inspect incoming XML.
elem
Node | MessageEvent
The received XML node. For BOSH connections, stanzas arrive wrapped in a <body> element. For WebSocket, the opening/closing <stream> tags are passed as self-closing elements.
conn.xmlInput = (elem) => {
  console.log("IN:", new XMLSerializer().serializeToString(elem));
};

xmlOutput

xmlOutput(elem: Element): void
Called with each XML element just before it is transmitted to the server.
elem
Element
The outgoing XML element.
conn.xmlOutput = (elem) => {
  console.log("OUT:", new XMLSerializer().serializeToString(elem));
};

rawInput

rawInput(data: string): void
Called with the raw string data received from the server, before XML parsing. Useful for transport-level debugging.
data
string
The raw received string (e.g. the full HTTP response body for BOSH, or the raw WebSocket text frame payload).
conn.rawInput = (data) => console.log("RAW IN:", data);

rawOutput

rawOutput(data: string): void
Called with the raw string data that is about to be sent to the server.
data
string
The raw outgoing string.
conn.rawOutput = (data) => console.log("RAW OUT:", data);

Static Methods

Connection.addConnectionPlugin

static addConnectionPlugin(name: string, ptype: object): void
Registers a plugin prototype to be instantiated and attached to every new Connection object. The plugin is initialized by calling ptype.init(connection) immediately after the Connection constructor runs. This is the standard extension point for Strophe plugins.
name
string
required
The property name under which the plugin will be accessible on the connection instance (e.g. "muc"conn.muc).
ptype
object
required
The plugin prototype object. Must implement an init(connection) method.
const MyPlugin = {
  init(conn) {
    this._conn = conn;
    conn.addHandler(this._onMessage.bind(this), null, "message");
  },
  _onMessage(stanza) {
    console.log("Plugin received message:", stanza);
    return true;
  },
  sendCustomStanza() {
    this._conn.send(
      $msg({ to: "server.example.com" }).c("x", { xmlns: "my:plugin:ns" })
    );
  },
};

Strophe.Connection.addConnectionPlugin("myPlugin", MyPlugin);

// Now every new Connection has `conn.myPlugin`
const conn = new Strophe.Connection("/http-bind/");
conn.connect("alice@example.com", "pass", () => {
  conn.myPlugin.sendCustomStanza();
});

Build docs developers (and LLMs) love