@stomp/stompjs
- Version 7.2.0
- Published
- 472 kB
- No dependencies
- Apache-2.0 license
Install
npm i @stomp/stompjs
yarn add @stomp/stompjs
pnpm add @stomp/stompjs
Overview
STOMP client for Javascript and Typescript
Index
Classes
Client
- abort()
- ack()
- activate()
- active
- appendMissingNULLonIncoming
- beforeConnect
- begin()
- brokerURL
- commit()
- configure()
- connected
- connectedVersion
- connectHeaders
- connectionTimeout
- deactivate()
- debug
- discardWebsocketOnCommFailure
- disconnectHeaders
- forceBinaryWSFrames
- forceDisconnect()
- heartbeatIncoming
- heartbeatOutgoing
- heartbeatStrategy
- heartbeatToleranceMultiplier
- logRawCommunication
- maxReconnectDelay
- maxWebSocketChunkSize
- nack()
- onChangeState
- onConnect
- onDisconnect
- onHeartbeatLost
- onHeartbeatReceived
- onStompError
- onUnhandledFrame
- onUnhandledMessage
- onUnhandledReceipt
- onWebSocketClose
- onWebSocketError
- publish()
- reconnectDelay
- reconnectTimeMode
- splitLargeFrames
- state
- stompVersions
- subscribe()
- unsubscribe()
- watchForReceipt()
- webSocket
- webSocketFactory
StompConfig
- appendMissingNULLonIncoming
- beforeConnect
- brokerURL
- connectHeaders
- connectionTimeout
- debug
- discardWebsocketOnCommFailure
- disconnectHeaders
- forceBinaryWSFrames
- heartbeatIncoming
- heartbeatOutgoing
- heartbeatStrategy
- heartbeatToleranceMultiplier
- logRawCommunication
- maxReconnectDelay
- maxWebSocketChunkSize
- onChangeState
- onConnect
- onDisconnect
- onHeartbeatLost
- onHeartbeatReceived
- onStompError
- onUnhandledFrame
- onUnhandledMessage
- onUnhandledReceipt
- onWebSocketClose
- onWebSocketError
- reconnectDelay
- reconnectTimeMode
- splitLargeFrames
- stompVersions
- webSocketFactory
Interfaces
Enums
Type Aliases
Classes
class Client
class Client {}
STOMP Client Class.
Part of
@stomp/stompjs
.This class provides a robust implementation for connecting to and interacting with a STOMP-compliant messaging broker over WebSocket. It supports STOMP versions 1.2, 1.1, and 1.0.
Features: - Handles automatic reconnections. - Supports heartbeat mechanisms to detect and report communication failures. - Allows customization of connection and WebSocket behaviors through configurations. - Compatible with both browser environments and Node.js with polyfill support for WebSocket.
constructor
constructor(conf?: StompConfig);
Constructs a new STOMP client instance.
The constructor initializes default values and sets up no-op callbacks for all events. Configuration can be passed during construction, or updated later using
configure
.Example:
const client = new Client({brokerURL: 'wss://broker.example.com',reconnectDelay: 5000});Parameter conf
Optional configuration object to initialize the client with.
property active
readonly active: boolean;
Indicates whether the client is currently active.
A client is considered active if it is connected or actively attempting to reconnect.
Example:
if (client.active) {console.log('The client is active.');} else {console.log('The client is inactive.');}Returns
true
if the client is active, otherwisefalse
.
property appendMissingNULLonIncoming
appendMissingNULLonIncoming: boolean;
Workaround for a React Native WebSocket bug, where messages containing
NULL
are chopped.Enabling this appends a
NULL
character to incoming frames to ensure they remain valid STOMP packets.Warning: - For brokers that split large messages, this may cause data loss or connection termination.
Example:
client.appendMissingNULLonIncoming = true;
property beforeConnect
beforeConnect: (client: Client) => void | Promise<void>;
Callback executed before initiating a connection to the STOMP broker.
This callback allows users to modify connection options dynamically, such as updating credentials or connection parameters, before the connection is made.
As of version 5.1, this callback supports
async/await
, enabling seamless integration with asynchronous operations, such as fetching tokens or credentials.Example:
client.beforeConnect = async () => {const token = await fetchToken();client.connectHeaders = { Authorization: `Bearer ${token}` };};
property brokerURL
brokerURL: string;
The URL for the STOMP broker to connect to. Example:
"ws://broker.domain.com:15674/ws"
or"wss://broker.domain.com:15674/ws"
.Use this property to define the broker's WebSocket endpoint. Note: - Only one of
brokerURL
or [Client#webSocketFactory]Client#webSocketFactory needs to be set. - If both are provided, [Client#webSocketFactory]Client#webSocketFactory takes precedence. - When targeting environments without native WebSocket support, refer to [Polyfills]https://stomp-js.github.io/guide/stompjs/rx-stomp/ng2-stompjs/pollyfils-for-stompjs-v5.html.
property connected
readonly connected: boolean;
Indicates whether there is an active connection to the STOMP broker.
Usage:
if (client.connected) {console.log('Client is connected to the broker.');} else {console.log('No connection to the broker.');}Returns
true
if the client is currently connected,false
otherwise.
property connectedVersion
readonly connectedVersion: string;
The version of the STOMP protocol negotiated with the server during connection.
This is a **read-only** property and reflects the negotiated protocol version after a successful connection.
Example:
console.log('Connected STOMP version:', client.connectedVersion);Returns
The negotiated STOMP protocol version or
undefined
if not connected.
property connectHeaders
connectHeaders: StompHeaders;
Connection headers to be sent during the connection handshake.
Keys like
login
,passcode
, andhost
are commonly expected for most brokers. Although STOMP 1.2 specifies these keys as mandatory, consult your broker's documentation for additional requirements or alternative header usage.Example:
client.connectHeaders = {login: 'my-username',passcode: 'my-password',host: 'my-vhost'};
property connectionTimeout
connectionTimeout: number;
Timeout for establishing STOMP connection, in milliseconds.
If the connection is not established within this period, the attempt will fail. The default is
0
, meaning no timeout is set for connection attempts.Example:
client.connectionTimeout = 5000; // Fail connection if not established in 5 seconds
property debug
debug: debugFnType;
Set a custom debug function to capture debug messages.
By default, debug messages are discarded. To log messages to the console, you can use:
client.debug = (str) => {console.log(str);};**Note**: This method does not support configurable log levels, and the output can be verbose. Be cautious as debug messages may contain sensitive information, such as credentials or tokens.
property discardWebsocketOnCommFailure
discardWebsocketOnCommFailure: boolean;
Instruct the library to immediately terminate the socket on communication failures, even before the WebSocket is completely closed.
This is particularly useful in browser environments where WebSocket closure may get delayed, causing prolonged reconnection intervals under certain failure conditions.
Example:
client.discardWebsocketOnCommFailure = true; // Enable aggressive closing of WebSocketDefault value:
false
.
property disconnectHeaders
disconnectHeaders: StompHeaders;
Allows customization of the disconnection headers.
Any changes made during an active session will also be applied immediately.
Example:
client.disconnectHeaders = {receipt: 'custom-receipt-id'};
property forceBinaryWSFrames
forceBinaryWSFrames: boolean;
Forces all WebSocket frames to use binary transport, irrespective of payload type.
Default behavior determines frame type based on payload (e.g., binary data for ArrayBuffers).
Example:
client.forceBinaryWSFrames = true;
property heartbeatIncoming
heartbeatIncoming: number;
Interval (in milliseconds) for receiving heartbeat signals from the server.
Specifies the expected frequency of heartbeats sent by the server. Set to
0
to disable.Example:
client.heartbeatIncoming = 10000; // Expect a heartbeat every 10 seconds
property heartbeatOutgoing
heartbeatOutgoing: number;
Interval (in milliseconds) for sending heartbeat signals to the server.
Specifies how frequently heartbeats should be sent to the server. Set to
0
to disable.Example:
client.heartbeatOutgoing = 5000; // Send a heartbeat every 5 seconds
property heartbeatStrategy
heartbeatStrategy: TickerStrategy;
Strategy for sending outgoing heartbeats.
Options: -
TickerStrategy.Worker
: Uses Web Workers for sending heartbeats (recommended for long-running or background sessions). -TickerStrategy.Interval
: Uses standard JavaScriptsetInterval
(default).Note: - If Web Workers are unavailable (e.g., in Node.js), the
Interval
strategy is used automatically. - Web Workers are preferable in browsers for reducing disconnects when tabs are in the background.Example:
client.heartbeatStrategy = TickerStrategy.Worker;
property heartbeatToleranceMultiplier
heartbeatToleranceMultiplier: number;
Multiplier for adjusting tolerance when processing heartbeat signals.
Tolerance level is calculated using the multiplier:
tolerance = heartbeatIncoming * heartbeatToleranceMultiplier
. This helps account for delays in network communication or variations in timings.Default value is
2
.Example:
client.heartbeatToleranceMultiplier = 2.5; // Tolerates longer delays
property logRawCommunication
logRawCommunication: boolean;
Enable or disable logging of the raw communication with the broker.
When enabled, it logs the raw frames exchanged with the broker. If disabled, only the headers of the parsed frames will be logged.
**Caution**: Raw communication frames must contain valid UTF-8 strings, as any non-compliant data can cause errors in the logging process.
Changes to this setting will take effect during the next broker reconnect.
Example:
client.logRawCommunication = true; // Enable logging raw communication
property maxReconnectDelay
maxReconnectDelay: number;
Maximum delay (in milliseconds) between reconnection attempts when using exponential backoff.
Default is 15 minutes (
15 * 60 * 1000
milliseconds). If0
, there will be no upper limit.Example:
client.maxReconnectDelay = 10000; // Maximum wait time is 10 seconds
property maxWebSocketChunkSize
maxWebSocketChunkSize: number;
Maximum size (in bytes) for individual WebSocket chunks if [splitLargeFrames]Client#splitLargeFrames is enabled.
Default is 8 KB (
8 * 1024
bytes). This value has no effect if [splitLargeFrames]Client#splitLargeFrames isfalse
.
property onChangeState
onChangeState: (state: ActivationState) => void;
Callback invoked whenever the client's state changes.
This callback can be used to monitor transitions between various states, such as
ACTIVE
,INACTIVE
, orDEACTIVATING
. Note that in some scenarios, the client may transition directly fromACTIVE
toINACTIVE
without entering theDEACTIVATING
state.Example:
client.onChangeState = (state) => {console.log(`Client state changed to: ${state}`);};
property onConnect
onConnect: frameCallbackType;
Callback executed upon every successful connection to the STOMP broker.
This callback is invoked after the connection is established and the CONNECTED frame is received from the broker. It provides access to the broker's response frame, allowing users to parse its headers or other data.
Example:
client.onConnect = (frame) => {console.log('Connected to broker, session ID:', frame.headers['session']);};
property onDisconnect
onDisconnect: frameCallbackType;
Callback executed upon successful disconnection from the STOMP broker.
The callback is invoked when the DISCONNECT receipt is received from the broker. Note that due to the design of the STOMP protocol or communication interrupts, the DISCONNECT receipt may not always be received. For handling such cases, use [Client#onWebSocketClose]Client#onWebSocketClose.
Example:
client.onDisconnect = (frame) => {console.log('Disconnected successfully');};
property onHeartbeatLost
onHeartbeatLost: emptyCallbackType;
Callback invoked when no heartbeat is received from the broker within the acceptable interval, indicating a potential communication issue or connection failure.
This callback is triggered when the heartbeat interval defined by
heartbeatIncoming
elapses without a received heartbeat.**Note**: The library handles this condition internally and takes appropriate actions, such as marking the connection as failed. This callback is available for implementing custom recovery strategies or additional notifications.
Usage:
client.onHeartbeatLost = () => {console.error('Lost connection to the broker');};
property onHeartbeatReceived
onHeartbeatReceived: emptyCallbackType;
Callback invoked when a heartbeat message is received from the STOMP broker.
Heartbeats ensure that the connection remains active and responsive. This callback is executed on every received heartbeat. It is useful for monitoring connection health or logging heartbeat activity.
**Note**: The library handles heartbeats internally to maintain and verify connection status. Implementing this callback is optional and primarily for custom monitoring or debugging.
Usage:
client.onHeartbeatReceived = () => {console.log('Heartbeat received');};
property onStompError
onStompError: frameCallbackType;
Callback executed when an ERROR frame is received from the STOMP broker.
Receiving an ERROR frame typically indicates a problem with the subscription, message format, or protocol violation. The broker will usually close the connection after sending an ERROR frame.
Example:
client.onStompError = (frame) => {console.error('Broker reported an error:', frame.body);};
property onUnhandledFrame
onUnhandledFrame: frameCallbackType;
Callback invoked when a frame of an unknown or unexpected type is received from the broker.
This is intended as a fallback for handling unexpected or unsupported frames sent by the broker.
Usage:
client.onUnhandledFrame = (frame) => {console.warn('Unhandled frame received:', frame);};Parameter frame
The actual IFrame received from the broker.
property onUnhandledMessage
onUnhandledMessage: messageCallbackType;
Callback invoked for any unhandled messages received from the broker.
This is particularly useful for handling messages sent to RabbitMQ temporary queues or other queues where no explicit subscription exists. It can also be triggered by stray messages received while a subscription is being unsubscribed.
Usage:
client.onUnhandledMessage = (message) => {console.log('Unhandled message:', message);};Parameter message
The actual IMessage received.
property onUnhandledReceipt
onUnhandledReceipt: frameCallbackType;
Callback invoked when the broker sends a receipt indicating the completion of an operation. Receipts are typically requested using the [Client#watchForReceipt]Client#watchForReceipt function.
Usage Example: See [Client#watchForReceipt]Client#watchForReceipt.
Parameter frame
The actual IFrame received from the broker.
property onWebSocketClose
onWebSocketClose: closeEventCallbackType<any>;
Callback executed when the underlying WebSocket is closed.
This can occur due to various reasons, such as network interruptions or broker shutdown. The callback provides the WebSocket [CloseEvent]https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent, which contains details about the closure.
Example:
client.onWebSocketClose = (event) => {console.log('WebSocket closed. Code:', event.code);};
property onWebSocketError
onWebSocketError: wsErrorCallbackType<any>;
Callback executed when the underlying WebSocket raises an error.
This callback provides an [Event]https://developer.mozilla.org/en-US/docs/Web/API/Event representing the error raised by the WebSocket.
Example:
client.onWebSocketError = (event) => {console.error('WebSocket error:', event);};
property reconnectDelay
reconnectDelay: number;
Delay (in milliseconds) between reconnection attempts if the connection drops.
Set to
0
to disable automatic reconnections. The default value is5000
ms (5 seconds).Example:
client.reconnectDelay = 3000; // Attempt reconnection every 3 secondsclient.reconnectDelay = 0; // Disable automatic reconnection
property reconnectTimeMode
reconnectTimeMode: ReconnectionTimeMode;
Mode for determining the time interval between reconnection attempts.
Available modes: -
ReconnectionTimeMode.LINEAR
(default): Fixed delays between reconnection attempts. -ReconnectionTimeMode.EXPONENTIAL
: Delay doubles after each attempt, capped by [maxReconnectDelay]Client#maxReconnectDelay.Example:
client.reconnectTimeMode = ReconnectionTimeMode.EXPONENTIAL;client.reconnectDelay = 200; // Initial delay of 200 ms, doubles with each attemptclient.maxReconnectDelay = 2 * 60 * 1000; // Cap delay at 10 minutes
property splitLargeFrames
splitLargeFrames: boolean;
Enables splitting of large text WebSocket frames into smaller chunks.
This setting is enabled for brokers that support only chunked messages (e.g., Java Spring-based brokers). Default is
false
.Warning: - Should not be used with WebSocket-compliant brokers, as chunking may cause large message failures. - Binary WebSocket frames are never split.
Example:
client.splitLargeFrames = true;client.maxWebSocketChunkSize = 4096; // Allow chunks of 4 KB
property state
state: ActivationState;
Current activation state of the client.
Possible states: -
ActivationState.ACTIVE
: Client is connected or actively attempting to connect. -ActivationState.INACTIVE
: Client is disconnected and not attempting to reconnect. -ActivationState.DEACTIVATING
: Client is in the process of disconnecting.Note: The client may transition directly from
ACTIVE
toINACTIVE
without entering theDEACTIVATING
state.
property stompVersions
stompVersions: Versions;
STOMP protocol versions to use during the handshake. By default, the client will attempt versions
1.2
,1.1
, and1.0
in descending order of preference.Example:
// Configure the client to only use versions 1.1 and 1.0client.stompVersions = new Versions(['1.1', '1.0']);
property webSocket
readonly webSocket: IStompSocket;
Provides access to the underlying WebSocket instance. This property is **read-only**.
Example:
const webSocket = client.webSocket;if (webSocket) {console.log('WebSocket is connected:', webSocket.readyState === WebSocket.OPEN);}**Caution:** Directly interacting with the WebSocket instance (e.g., sending or receiving frames) can interfere with the proper functioning of this library. Such actions may cause unexpected behavior, disconnections, or invalid state in the library's internal mechanisms.
Instead, use the library's provided methods to manage STOMP communication.
Returns
The WebSocket instance used by the STOMP handler, or
undefined
if not connected.
property webSocketFactory
webSocketFactory: () => IStompSocket;
A function that returns a WebSocket or a similar object (e.g., SockJS) to establish connections.
This is an alternative to [Client#brokerURL]Client#brokerURL. Using this allows finer control over WebSocket creation, especially for custom wrappers or when working in non-standard environments.
Example:
client.webSocketFactory = function () {return new WebSocket("ws://my-custom-websocket-endpoint");};// Typical usage with SockJSclient.webSocketFactory= function () {return new SockJS("http://broker.329broker.com/stomp");};Note: - If both [Client#brokerURL]Client#brokerURL and this property are set, the factory will be used. - Refer to [Polyfills Guide]https://stomp-js.github.io/guide/stompjs/rx-stomp/ng2-stompjs/pollyfils-for-stompjs-v5.html when running in environments without native WebSocket support.
method abort
abort: (transactionId: string) => void;
Aborts a transaction.
It is strongly recommended to call [abort]ITransaction#abort directly on the transaction object returned by [client#begin]Client#begin.
Example:
const tx = client.begin();// Perform operations under this transactiontx.abort(); // Abort the transactionParameter transactionId
The ID of the transaction to abort.
method ack
ack: (messageId: string, subscriptionId: string, headers?: StompHeaders) => void;
Acknowledges receipt of a message. Typically, this should be done by calling [ack]IMessage#ack directly on the IMessage instance passed to the subscription callback.
Example:
const callback = (message) => {// Process the messagemessage.ack(); // Acknowledge the message};client.subscribe("/queue/example", callback, { ack: "client" });Parameter messageId
The ID of the message to acknowledge.
Parameter subscriptionId
The ID of the subscription.
Parameter headers
Optional headers for the acknowledgment frame.
method activate
activate: () => void;
Activates the client, initiating a connection to the STOMP broker.
On activation, the client attempts to connect and sets its state to
ACTIVE
. If the connection is lost, it will automatically retry based onreconnectDelay
ormaxReconnectDelay
. IfreconnectTimeMode
is set toEXPONENTIAL
, the reconnect delay increases exponentially.To stop reconnection attempts and disconnect, call [Client#deactivate]Client#deactivate.
Example:
client.activate(); // Connect to the brokerIf the client is currently
DEACTIVATING
, connection is delayed until the deactivation process completes.
method begin
begin: (transactionId?: string) => ITransaction;
Starts a new transaction. The returned ITransaction object provides methods for [commit]ITransaction#commit and [abort]ITransaction#abort.
If
transactionId
is not provided, the library generates a unique ID internally.Example:
const tx = client.begin(); // Auto-generated ID// Or explicitly specify a transaction IDconst tx = client.begin("my-transaction-id");Parameter transactionId
Optional transaction ID.
Returns
An instance of ITransaction.
method commit
commit: (transactionId: string) => void;
Commits a transaction.
It is strongly recommended to call [commit]ITransaction#commit on the transaction object returned by [client#begin]Client#begin.
Example:
const tx = client.begin();// Perform operations under this transactiontx.commit();Parameter transactionId
The ID of the transaction to commit.
method configure
configure: (conf: StompConfig) => void;
Updates the client's configuration.
All properties in the provided configuration object will override the current settings.
Additionally, a warning is logged if
maxReconnectDelay
is configured to a value lower thanreconnectDelay
, andmaxReconnectDelay
is adjusted to matchreconnectDelay
.Example:
client.configure({reconnectDelay: 3000,maxReconnectDelay: 10000});Parameter conf
Configuration object containing the new settings.
method deactivate
deactivate: (options?: { force?: boolean }) => Promise<void>;
Disconnects the client and stops the automatic reconnection loop.
If there is an active STOMP connection at the time of invocation, the appropriate callbacks will be triggered during the shutdown sequence. Once deactivated, the client will enter the
INACTIVE
state, and no further reconnection attempts will be made.**Behavior**: - If there is no active WebSocket connection, this method resolves immediately. - If there is an active connection, the method waits for the underlying WebSocket to properly close before resolving. - Multiple calls to this method are safe. Each invocation resolves upon completion. - To reactivate, call [Client#activate]Client#activate.
**Experimental Option:** - By specifying the
force: true
option, the WebSocket connection is discarded immediately, bypassing both the STOMP and WebSocket shutdown sequences. - **Caution:** Usingforce: true
may leave the WebSocket in an inconsistent state, and brokers may not immediately detect the termination.Example:
// Graceful disconnectawait client.deactivate();// Forced disconnect to speed up shutdown when the connection is staleawait client.deactivate({ force: true });Parameter options
Configuration options for deactivation. Use
force: true
for immediate shutdown.Returns
A Promise that resolves when the deactivation process completes.
method forceDisconnect
forceDisconnect: () => void;
Forces a disconnect by directly closing the WebSocket.
Unlike a normal disconnect, this does not send a DISCONNECT sequence to the broker but instead closes the WebSocket connection directly. After forcing a disconnect, the client will automatically attempt to reconnect based on its
reconnectDelay
configuration.**Note:** To prevent further reconnect attempts, call [Client#deactivate]Client#deactivate.
Example:
client.forceDisconnect();
method nack
nack: ( messageId: string, subscriptionId: string, headers?: StompHeaders) => void;
Rejects a message (negative acknowledgment). Like acknowledgments, this should typically be done by calling [nack]IMessage#nack directly on the IMessage instance passed to the subscription callback.
Example:
const callback = (message) => {// Process the messageif (isError(message)) {message.nack(); // Reject the message}};client.subscribe("/queue/example", callback, { ack: "client" });Parameter messageId
The ID of the message to negatively acknowledge.
Parameter subscriptionId
The ID of the subscription.
Parameter headers
Optional headers for the NACK frame.
method publish
publish: (params: IPublishParams) => void;
Sends a message to the specified destination on the STOMP broker.
The
body
must be astring
. For non-string payloads (e.g., JSON), encode it as a string before sending. If sending binary data, use thebinaryBody
parameter as a [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array).**Content-Length Behavior**: - For non-binary messages, the
content-length
header is added by default. - Thecontent-length
header can be skipped for text frames by settingskipContentLengthHeader: true
in the parameters. - For binary messages, thecontent-length
header is always included.**Notes**: - Ensure that brokers support binary frames before using
binaryBody
. - Sending messages with NULL octets and missingcontent-length
headers can cause brokers to disconnect and throw errors.Example:
// Basic text messageclient.publish({ destination: "/queue/test", body: "Hello, STOMP" });// Text message with additional headersclient.publish({ destination: "/queue/test", headers: { priority: 9 }, body: "Hello, STOMP" });// Skip content-length headerclient.publish({ destination: "/queue/test", body: "Hello, STOMP", skipContentLengthHeader: true });// Binary messageconst binaryData = new Uint8Array([1, 2, 3, 4]);client.publish({destination: '/topic/special',binaryBody: binaryData,headers: { 'content-type': 'application/octet-stream' }});
method subscribe
subscribe: ( destination: string, callback: messageCallbackType, headers?: StompHeaders) => StompSubscription;
Subscribes to a destination on the STOMP broker.
The callback is triggered for each message received from the subscribed destination. The message is passed as an IMessage instance.
**Subscription ID**: - If no
id
is provided inheaders
, the library generates a unique subscription ID automatically. - Provide an explicitid
inheaders
if you wish to manage the subscription ID manually.Example:
const callback = (message) => {console.log("Received message:", message.body);};// Auto-generated subscription IDconst subscription = client.subscribe("/queue/test", callback);// Explicit subscription IDconst mySubId = "my-subscription-id";const subscription = client.subscribe("/queue/test", callback, { id: mySubId });Parameter destination
Destination to subscribe to.
Parameter callback
Function invoked for each received message.
Parameter headers
Optional headers for subscription, such as
id
.Returns
A StompSubscription which can be used to manage the subscription.
method unsubscribe
unsubscribe: (id: string, headers?: StompHeaders) => void;
Unsubscribes from a subscription on the STOMP broker.
Prefer using the
unsubscribe
method directly on the StompSubscription returned fromsubscribe
for cleaner management:const subscription = client.subscribe("/queue/test", callback);// Unsubscribe using the subscription objectsubscription.unsubscribe();This method can also be used directly with the subscription ID.
Example:
client.unsubscribe("my-subscription-id");Parameter id
Subscription ID to unsubscribe.
Parameter headers
Optional headers to pass for the UNSUBSCRIBE frame.
method watchForReceipt
watchForReceipt: (receiptId: string, callback: frameCallbackType) => void;
Monitors for a receipt acknowledgment from the broker for specific operations.
Add a
receipt
header to the operation (like subscribe or publish), and use this method with the same receipt ID to detect when the broker has acknowledged the operation's completion.The callback is invoked with the corresponding IFrame when the receipt is received.
Example:
const receiptId = "unique-receipt-id";client.watchForReceipt(receiptId, (frame) => {console.log("Operation acknowledged by the broker:", frame);});// Attach the receipt header to an operationclient.publish({ destination: "/queue/test", headers: { receipt: receiptId }, body: "Hello" });Parameter receiptId
Unique identifier for the receipt.
Parameter callback
Callback function invoked on receiving the RECEIPT frame.
class CompatClient
class CompatClient extends Client {}
Available for backward compatibility, please shift to using Client.
**Deprecated**
Part of
@stomp/stompjs
.To upgrade, please follow the [Upgrade Guide](https://stomp-js.github.io/guide/stompjs/upgrading-stompjs.html)
property heartbeat
heartbeat: { incoming: number; outgoing: number };
Available for backward compatibility, renamed to [Client#heartbeatIncoming]Client#heartbeatIncoming [Client#heartbeatOutgoing]Client#heartbeatOutgoing.
**Deprecated**
property maxWebSocketFrameSize
maxWebSocketFrameSize: number;
It is no op now. No longer needed. Large packets work out of the box.
property onreceipt
onreceipt: frameCallbackType;
Available for backward compatibility, renamed to [Client#onUnhandledReceipt]Client#onUnhandledReceipt. Prefer using [Client#watchForReceipt]Client#watchForReceipt.
**Deprecated**
property onreceive
onreceive: messageCallbackType;
Available for backward compatibility, renamed to [Client#onUnhandledMessage]Client#onUnhandledMessage.
**Deprecated**
property version
readonly version: string;
Available for backward compatibility, renamed to [Client#connectedVersion]Client#connectedVersion.
**Deprecated**
property ws
readonly ws: any;
Available for backward compatibility, renamed to [Client#webSocket]Client#webSocket.
**Deprecated**
method connect
connect: (...args: any[]) => void;
Available for backward compatibility, please shift to using [Client#activate]Client#activate.
**Deprecated**
The
connect
method accepts different number of arguments and types. See the Overloads list. Use the version with headers to pass your broker specific options.overloads: - connect(headers, connectCallback) - connect(headers, connectCallback, errorCallback) - connect(login, passcode, connectCallback) - connect(login, passcode, connectCallback, errorCallback) - connect(login, passcode, connectCallback, errorCallback, closeEventCallback) - connect(login, passcode, connectCallback, errorCallback, closeEventCallback, host)
params: - headers, see [Client#connectHeaders]Client#connectHeaders - connectCallback, see [Client#onConnect]Client#onConnect - errorCallback, see [Client#onStompError]Client#onStompError - closeEventCallback, see [Client#onWebSocketClose]Client#onWebSocketClose - login [String], see [Client#connectHeaders](../classes/Client.html#connectHeaders) - passcode [String], [Client#connectHeaders](../classes/Client.html#connectHeaders) - host [String], see [Client#connectHeaders](../classes/Client.html#connectHeaders)
To upgrade, please follow the [Upgrade Guide](../additional-documentation/upgrading.html)
method disconnect
disconnect: (disconnectCallback?: any, headers?: StompHeaders) => void;
Available for backward compatibility, please shift to using [Client#deactivate]Client#deactivate.
**Deprecated**
See: [Client#onDisconnect]Client#onDisconnect, and [Client#disconnectHeaders]Client#disconnectHeaders
To upgrade, please follow the [Upgrade Guide](../additional-documentation/upgrading.html)
method send
send: ( destination: string, headers?: { [key: string]: any }, body?: string) => void;
Available for backward compatibility, use [Client#publish]Client#publish.
Send a message to a named destination. Refer to your STOMP broker documentation for types and naming of destinations. The headers will, typically, be available to the subscriber. However, there may be special purpose headers corresponding to your STOMP broker.
**Deprecated**, use [Client#publish]Client#publish
Note: Body must be String. You will need to covert the payload to string in case it is not string (e.g. JSON)
client.send("/queue/test", {priority: 9}, "Hello, STOMP");// If you want to send a message with a body, you must also pass the headers argument.client.send("/queue/test", {}, "Hello, STOMP");To upgrade, please follow the [Upgrade Guide](../additional-documentation/upgrading.html)
class Stomp
class Stomp {}
property WebSocketClass
static WebSocketClass: any;
In case you need to use a non standard class for WebSocket.
For example when using within NodeJS environment:
StompJs = require('../../esm5/');Stomp = StompJs.Stomp;Stomp.WebSocketClass = require('websocket').w3cwebsocket;**Deprecated**
It will be removed in next major version. Please switch to Client using [Client#webSocketFactory]Client#webSocketFactory.
method client
static client: (url: string, protocols?: string[]) => CompatClient;
This method creates a WebSocket client that is connected to the STOMP server located at the url.
var url = "ws://localhost:61614/stomp";var client = Stomp.client(url);**Deprecated**
It will be removed in next major version. Please switch to Client using [Client#brokerURL]Client#brokerURL.
method over
static over: (ws: any) => CompatClient;
This method is an alternative to [Stomp#client]Stomp#client to let the user specify the WebSocket to use (either a standard HTML5 WebSocket or a similar object).
In order to support reconnection, the function Client._connect should be callable more than once. While reconnecting a new instance of underlying transport (TCP Socket, WebSocket or SockJS) will be needed. So, this function alternatively allows passing a function that should return a new instance of the underlying socket.
var client = Stomp.over(function(){return new WebSocket('ws://localhost:15674/ws')});**Deprecated**
It will be removed in next major version. Please switch to Client using [Client#webSocketFactory]Client#webSocketFactory.
class StompConfig
class StompConfig {}
Configuration options for STOMP Client, each key corresponds to field by the same name in Client. This can be passed to the constructor of Client or to [Client#configure]Client#configure.
Part of
@stomp/stompjs
.
property appendMissingNULLonIncoming
appendMissingNULLonIncoming?: boolean;
See [Client#appendMissingNULLonIncoming]Client#appendMissingNULLonIncoming.
property beforeConnect
beforeConnect?: (client: Client) => void | Promise<void>;
See [Client#beforeConnect]Client#beforeConnect.
property brokerURL
brokerURL?: string;
See [Client#brokerURL]Client#brokerURL.
property connectHeaders
connectHeaders?: StompHeaders;
See [Client#connectHeaders]Client#connectHeaders.
property connectionTimeout
connectionTimeout?: number;
See [Client#connectionTimeout]Client#connectionTimeout.
property debug
debug?: debugFnType;
See [Client#debug]Client#debug.
property discardWebsocketOnCommFailure
discardWebsocketOnCommFailure?: boolean;
See [Client#discardWebsocketOnCommFailure]Client#discardWebsocketOnCommFailure.
property disconnectHeaders
disconnectHeaders?: StompHeaders;
See [Client#disconnectHeaders]Client#disconnectHeaders.
property forceBinaryWSFrames
forceBinaryWSFrames?: boolean;
See [Client#forceBinaryWSFrames]Client#forceBinaryWSFrames.
property heartbeatIncoming
heartbeatIncoming?: number;
See [Client#heartbeatIncoming]Client#heartbeatIncoming.
property heartbeatOutgoing
heartbeatOutgoing?: number;
See [Client#heartbeatOutgoing]Client#heartbeatOutgoing.
property heartbeatStrategy
heartbeatStrategy?: TickerStrategy;
See [Client#heartbeatStrategy]Client#heartbeatStrategy.
property heartbeatToleranceMultiplier
heartbeatToleranceMultiplier?: number;
See [Client#heartbeatToleranceMultiplier]Client#heartbeatToleranceMultiplier.
property logRawCommunication
logRawCommunication?: boolean;
See [Client#logRawCommunication]Client#logRawCommunication.
property maxReconnectDelay
maxReconnectDelay?: number;
See [Client#maxReconnectDelay]Client#maxReconnectDelay
property maxWebSocketChunkSize
maxWebSocketChunkSize?: number;
See [Client#maxWebSocketChunkSize]Client#maxWebSocketChunkSize.
property onChangeState
onChangeState?: (state: ActivationState) => void;
See [Client#onChangeState]Client#onChangeState.
property onConnect
onConnect?: frameCallbackType;
See [Client#onConnect]Client#onConnect.
property onDisconnect
onDisconnect?: frameCallbackType;
See [Client#onDisconnect]Client#onDisconnect.
property onHeartbeatLost
onHeartbeatLost?: emptyCallbackType;
See [Client#onHeartbeatLost]Client#onHeartbeatLost.
property onHeartbeatReceived
onHeartbeatReceived?: emptyCallbackType;
See [Client#onHeartbeatReceived]Client#onHeartbeatReceived.
property onStompError
onStompError?: frameCallbackType;
See [Client#onStompError]Client#onStompError.
property onUnhandledFrame
onUnhandledFrame?: frameCallbackType;
See [Client#onUnhandledFrame]Client#onUnhandledFrame.
property onUnhandledMessage
onUnhandledMessage?: messageCallbackType;
See [Client#onUnhandledMessage]Client#onUnhandledMessage.
property onUnhandledReceipt
onUnhandledReceipt?: frameCallbackType;
See [Client#onUnhandledReceipt]Client#onUnhandledReceipt.
property onWebSocketClose
onWebSocketClose?: closeEventCallbackType<any>;
See [Client#onWebSocketClose]Client#onWebSocketClose.
property onWebSocketError
onWebSocketError?: wsErrorCallbackType<any>;
See [Client#onWebSocketError]Client#onWebSocketError.
property reconnectDelay
reconnectDelay?: number;
See [Client#reconnectDelay]Client#reconnectDelay.
property reconnectTimeMode
reconnectTimeMode?: ReconnectionTimeMode;
See [Client#reconnectTimeMode]Client#reconnectTimeMode
property splitLargeFrames
splitLargeFrames?: boolean;
See [Client#splitLargeFrames]Client#splitLargeFrames.
property stompVersions
stompVersions?: Versions;
See [Client#stompVersions]Client#stompVersions.
property webSocketFactory
webSocketFactory?: () => any;
See [Client#webSocketFactory]Client#webSocketFactory.
class StompHeaders
class StompHeaders {}
STOMP headers. Many function calls will accept headers as parameters. The headers sent by Broker will be available as [IFrame#headers]IFrame#headers.
key
andvalue
must be valid strings. In addition,key
must not containCR
,LF
, or:
.Part of
@stomp/stompjs
.
class Versions
class Versions {}
Supported STOMP versions
Part of
@stomp/stompjs
.
constructor
constructor(versions: string[]);
Takes an array of versions, typical elements '1.2', '1.1', or '1.0'
You will be creating an instance of this class if you want to override supported versions to be declared during STOMP handshake.
property V1_0
static V1_0: string;
Indicates protocol version 1.0
property V1_1
static V1_1: string;
Indicates protocol version 1.1
property V1_2
static V1_2: string;
Indicates protocol version 1.2
property versions
versions: string[];
method protocolVersions
protocolVersions: () => string[];
Used while creating a WebSocket
method supportedVersions
supportedVersions: () => string;
Used as part of CONNECT STOMP Frame
Interfaces
interface IFrame
interface IFrame {}
It represents a STOMP frame. Many of the callbacks pass an IFrame received from the STOMP broker. For advanced usage you might need to access [headers]IFrame#headers.
Part of
@stomp/stompjs
.IMessage is an extended IFrame.
property binaryBody
readonly binaryBody: Uint8Array;
body as Uint8Array
property body
readonly body: string;
body of the frame as string
property command
command: string;
STOMP Command
property headers
headers: StompHeaders;
Headers, key value pairs.
property isBinaryBody
isBinaryBody: boolean;
Is this frame binary (based on whether body/binaryBody was passed when creating this frame).
interface IMessage
interface IMessage extends IFrame {}
Instance of Message will be passed to [subscription callback]Client#subscribe and [Client#onUnhandledMessage]Client#onUnhandledMessage. Since it is an extended IFrame, you can access [headers]IFrame#headers and [body]IFrame#body as properties.
Part of
@stomp/stompjs
.See [Client#subscribe]Client#subscribe for example.
property ack
ack: (headers?: StompHeaders) => void;
When subscribing with manual acknowledgement, call this method on the message to ACK the message.
See [Client#ack]Client#ack for an example.
property nack
nack: (headers?: StompHeaders) => void;
When subscribing with manual acknowledgement, call this method on the message to NACK the message.
See [Client#nack]Client#nack for an example.
interface IPublishParams
interface IPublishParams {}
Parameters for [Client#publish]Client#publish. Aliased as publishParams as well.
Part of
@stomp/stompjs
.
property binaryBody
binaryBody?: Uint8Array;
binary body (optional)
property body
body?: string;
body (optional)
property destination
destination: string;
destination end point
property headers
headers?: StompHeaders;
headers (optional)
property skipContentLengthHeader
skipContentLengthHeader?: boolean;
By default, a
content-length
header will be added in the Frame to the broker. Set it totrue
for the header to be skipped.
interface ITransaction
interface ITransaction {}
A Transaction is created by calling [Client#begin]Client#begin
Part of
@stomp/stompjs
.
property abort
abort: () => void;
Abort this transaction. See [Client#abort]Client#abort for an example.
property commit
commit: () => void;
Commit this transaction. See [Client#commit]Client#commit for an example.
property id
id: string;
You will need to access this to send, ack, or nack within this transaction.
interface StompSubscription
interface StompSubscription {}
Call [Client#subscribe]Client#subscribe to create a StompSubscription.
Part of
@stomp/stompjs
.
property id
id: string;
Id associated with this subscription.
property unsubscribe
unsubscribe: (headers?: StompHeaders) => void;
Unsubscribe. See [Client#unsubscribe]Client#unsubscribe for an example.
Enums
enum ActivationState
enum ActivationState { ACTIVE = 0, DEACTIVATING = 1, INACTIVE = 2,}
Possible activation state
enum ReconnectionTimeMode
enum ReconnectionTimeMode { LINEAR = 0, EXPONENTIAL = 1,}
Possible reconnection wait time modes
member EXPONENTIAL
EXPONENTIAL = 1
member LINEAR
LINEAR = 0
enum StompSocketState
enum StompSocketState { CONNECTING = 0, OPEN = 1, CLOSING = 2, CLOSED = 3,}
Possible states for the IStompSocket
enum TickerStrategy
enum TickerStrategy { Interval = 'interval', Worker = 'worker',}
Possible ticker strategies for outgoing heartbeat ping
Type Aliases
type closeEventCallbackType
type closeEventCallbackType<T = any> = (evt: T) => void;
This callback will receive a [CloseEvent]https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent as parameter.
Part of
@stomp/stompjs
.
type debugFnType
type debugFnType = (msg: string) => void;
This callback will receive a
string
as a parameter.Part of
@stomp/stompjs
.
type emptyCallbackType
type emptyCallbackType = () => void;
This callback is an "Event" only callback, no parameters provided.
Part of
@stomp/stompjs
.
type Frame
type Frame = IFrame;
Alias for IFrame
type frameCallbackType
type frameCallbackType = ((frame: IFrame) => void) | (() => void);
This callback will receive a IFrame as parameter.
Part of
@stomp/stompjs
.
type Message
type Message = IMessage;
Aliased to IMessage.
Part of
@stomp/stompjs
.
type messageCallbackType
type messageCallbackType = (message: IMessage) => void;
This callback will receive a IMessage as parameter.
Part of
@stomp/stompjs
.
type publishParams
type publishParams = IPublishParams;
Backward compatibility, switch to IPublishParams.
type wsErrorCallbackType
type wsErrorCallbackType<T = any> = (evt: T) => void;
This callback will receive an [Event]https://developer.mozilla.org/en-US/docs/Web/API/Event as parameter.
Part of
@stomp/stompjs
.
Package Files (12)
Dependencies (0)
No dependencies.
Dev Dependencies (19)
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@stomp/stompjs
.
- Markdown[](https://www.jsdocs.io/package/@stomp/stompjs)
- HTML<a href="https://www.jsdocs.io/package/@stomp/stompjs"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 5353 ms. - Missing or incorrect documentation? Open an issue for this package.