Webstomp Client
webstomp-client is a JavaScript library providing a STOMP client over WebSockets for both browser and Node.js environments. Currently at version 1.2.6, it does not follow a fixed release cadence but rather ships updates as needed, addressing bug fixes and minor enhancements. This project is an active fork of the original `stomp-websocket` library by Jeff Mesnil and Jeff Lindsay, having been rewritten in ES6 to modernize its codebase and integrate community-contributed pull requests that were pending in the upstream project. Its key differentiators include modern ES6 syntax, built-in TypeScript type definitions, and explicit support for supplying custom WebSocket implementations (e.g., `ws` or `sockjs-client` in Node.js) via the `webstomp.over()` method, rather than relying solely on a global `WebSocket` object like its predecessor or browser-only alternatives. For browser environments, it automatically uses the global `WebSocket` object. It provides a robust API for connecting, subscribing, sending messages, and handling disconnections with STOMP servers like RabbitMQ Web-STOMP.
Common errors
-
TypeError: webstomp.client is not a function
cause Attempting to use `webstomp.client()` in Node.js where `WebSocket` is not globally available, or trying to use `client` as a named import after v1.2.3.fixFor Node.js, use `webstomp.over(new WebSocket(url))` with a custom WebSocket implementation like `ws`. Ensure you are using the default import: `import webstomp from 'webstomp-client';`. -
ReferenceError: WebSocket is not defined
cause Using `webstomp.client(url)` in a Node.js environment without globally polyfilling the `WebSocket` object.fixIn Node.js, explicitly use `webstomp.over(ws_instance)` and pass an instance of a Node.js WebSocket client (e.g., from the `ws` package). Alternatively, you could polyfill `global.WebSocket = require('ws');` but `webstomp.over` is the idiomatic way. -
TS2305: Module '"webstomp-client"' has no exported member 'Client'.
cause Trying to import the `Client` type (or `Frame` type) as a value import.fixUse a type-only import: `import type { Client } from 'webstomp-client';`.
Warnings
- breaking Version 1.2.3 removed mixed (named and default) exports. The library now exclusively uses a default export. If you were using named imports like `import { client, over } from 'webstomp-client';`, these will break.
- gotcha In Node.js environments, `webstomp-client` does not provide a default WebSocket implementation. You must explicitly provide a WebSocket-alike object instance (e.g., from the `ws` or `sockjs-client` packages) to the `webstomp.over()` method.
- gotcha The `connect` method has multiple overloads for parameters (headers vs. login/passcode). Ensure you pass parameters correctly to avoid connection issues.
- gotcha When connecting to SockJS-based STOMP servers, it's often recommended to disable heartbeats by setting `heartbeat: false` in the options object passed to `client()` or `over()`.
Install
-
npm install webstomp-client -
yarn add webstomp-client -
pnpm add webstomp-client
Imports
- webstomp
import { webstomp } from 'webstomp-client';import webstomp from 'webstomp-client';
- Client (type)
import type { Client } from 'webstomp-client'; - Frame (type)
import type { Frame } from 'webstomp-client'; - webstomp (CommonJS)
const webstomp = require('webstomp-client');
Quickstart
import webstomp from 'webstomp-client';
import WebSocket from 'ws'; // For Node.js, install 'ws': npm install ws
const WEBSOCKET_URL = process.env.STOMP_WS_URL ?? 'ws://localhost:15674/ws'; // Example: RabbitMQ Web-STOMP
const STOMP_USER = process.env.STOMP_USER ?? 'guest';
const STOMP_PASS = process.env.STOMP_PASS ?? 'guest';
async function runStompClient() {
console.log(`Attempting to connect to STOMP WebSocket at: ${WEBSOCKET_URL}`);
// In Node.js, a WebSocket implementation must be explicitly provided to webstomp.over()
// The protocols array ensures the WebSocket connection is established with STOMP-compatible subprotocols.
const ws = new WebSocket(WEBSOCKET_URL, ['v10.stomp', 'v11.stomp', 'v12.stomp']);
const client = webstomp.over(ws, {
debug: true,
heartbeat: { incoming: 10000, outgoing: 10000 } // Configure heartbeats
});
client.connect(
{ login: STOMP_USER, passcode: STOMP_PASS },
(frame: webstomp.Frame) => {
console.log('Successfully connected to STOMP server:', frame.headers['session']);
client.subscribe('/queue/example', (message: webstomp.Frame) => {
console.log('Received message:', message.body);
}, { id: 'my-subscription' }); // Include a unique ID for the subscription
console.log('Subscribed to /queue/example');
setTimeout(() => {
const messageBody = `Hello from webstomp-client at ${new Date().toISOString()}`;
client.send('/queue/example', messageBody, { 'content-type': 'text/plain' });
console.log('Sent message:', messageBody);
}, 2000);
setTimeout(() => {
client.disconnect(() => {
console.log('Disconnected from STOMP server.');
ws.close();
});
}, 5000);
},
(error: webstomp.Frame | CloseEvent) => {
console.error('STOMP connection error:', error);
if (error instanceof CloseEvent) {
console.error(`WebSocket closed with code ${error.code} and reason: ${error.reason}`);
}
ws.close();
}
);
ws.onopen = () => console.log('WebSocket connection opened.');
ws.onclose = () => console.log('WebSocket connection closed.');
ws.onerror = (err: Event) => console.error('WebSocket error:', err);
}
runStompClient().catch(console.error);