npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

stomp-react-hooks

v1.1.1

Published

A powerful React hook-based STOMP over WebSocket client with middleware, offline queue, and typed subscriptions.

Downloads

41

Readme

stomp-react-hooks

An advanced React STOMP WebSocket client with powerful hooks, adaptive throttling, schema validation, session recovery, middleware support, and role-based access control.


🌟 Features

  • ✅ React Hook API**: useStompClient, useStompTopics, useStompReplay, useStompStatus
  • 🔄 Adaptive Throttling**: Auto-optimizes message flow
  • 🔁 Offline Queue**: Stores unsent messages when disconnected
  • 🔐 Schema Validation**: Safe, typed messaging via JSON Schema
  • 🔑 Role-Based Access Control**: Secure topic-level access
  • 🔧 Middleware**: Modify inbound/outbound messages
  • 🧠 Shared STOMP Context**: Easy access across your app
  • 🧲 Event Bus**: Global connection/message listeners
  • ⚡ Retry Logic**: Auto reconnect with exponential backoff

📦 Installation

npm install stomp-react-hooks

Peer dependencies: react, @stomp/stompjs


🧪 Quick Start

import React from "react";
import {
    useStompClient,
    useStompTopics,
    registerSchema,
} from "stomp-react-hooks";

const TOPIC = "/app/chat/messages";

registerSchema(TOPIC, {
    type: "object",
    properties: {
        id: {type: "string"},
        user: {type: "string"},
        text: {type: "string"}
    },
    required: ["id", "user", "text"]
});

function Chat() {
    const {connected, send, subscribeTyped} = useStompClient({
        brokerURL: "ws://localhost:8080/ws",
        enableDebug: true,
        userRole: "user"
    });

    const messages = useStompTopics([TOPIC]);

    React.useEffect(() => {
        const sub = subscribeTyped(TOPIC, (msg) => {
            console.log("Received:", msg);
        });
        return () => sub?.unsubscribe();
    }, []);

    return (
        <>
            <button onClick={() => send(TOPIC, {
                id: Date.now().toString(), user: "user", text: "Hello!"
            })}>Send
            </button>

            <ul>
                {messages[TOPIC]?.map(msg => (
                    <li key={msg.id}><b>{msg.user}:</b> {msg.text}</li>
                ))}
            </ul>
        </>
    );
}

⚙️ useStompClient(config)

Manages a STOMP connection and subscriptions.

Options:

{
    brokerURL: string;
    namespace ? : string;
    connectHeaders ? : Record<string, string> | (() => Promise<Record<string, string>>);
    userRole ? : string;
    userAttributes ? : Record<string, any>;
    enableDebug ? : boolean;
    maxRetryAttempts ? : number;
}

Returns:

  • client: The STOMP client
  • connected: Connection status
  • send(destination, body, headers?)
  • subscribeTyped<T>(destination, handler, timeoutMs?)
  • subscribe(destination, handler)
  • reconnect()

🧠 Shared Context Setup

import {StompProvider, useStomp} from "stomp-react-hooks/context/StompContext";

export function App() {
    return (
        <StompProvider config={{brokerURL: "ws://localhost:8080/ws"}}>
            <Chat/>
        </StompProvider>
    );
}

function Chat() {
    const {subscribeTyped, send} = useStomp();
    // ...
}

🔔 subscribe(destination, handler)

Basic topic subscription without schema validation or parsing.

const {subscribe} = useStomp();

subscribe("topic/my-raw-event", (msg) => {
    console.log("Raw STOMP message:", msg.body);
});

📦 subscribeTyped<T>(destination, handler, timeoutMs?)

Typed topic subscription with middleware + schema validation.

const {subscribeTyped} = useStomp();

subscribeTyped<{ id: string; type: string }>("topic/one-dice:123", (data) => {
    console.log("Validated and typed payload:", data);
});

✅ Automatically applies middleware and schema validation if registered.


✅ Ensures clean disconnection when auth expires or the app resets.



🔐 Auth Header Usage

Static Headers:

useStompClient({
    brokerURL: "ws://...",
    connectHeaders: {
        Authorization: "Bearer yourToken"
    }
});

Dynamic (Async) Headers:

useStompClient({
    brokerURL: "ws://...",
    connectHeaders: async () => {
        const token = await fetch('/auth/token');
        return {Authorization: `Bearer ${token}`};
    }
});

🔄 Offline Support

Messages sent while disconnected are buffered and auto-flushed after reconnect:

send('/topic/chat', {msg: "Offline message"});

⚡ Middleware

stomp-react-hooks supports powerful middleware hooks that let you transform, encrypt, log, or filter messages automatically.

✨ Use Case Examples:

import {useMiddleware} from "stomp-react-hooks";

useMiddleware.addInbound((msg) => {
    msg.receivedAt = Date.now();
    return msg;
});

useMiddleware.addOutbound((msg) => {
    console.debug("Sending:", msg);
    return msg;
});

If you want to encrypt all messages with AES, you can create a setup like this:

// index.tsx
import {setupEncryptionMiddleware} from "@/utils/encryptionMiddleware";

// Set key from .env, auth, or props
setupEncryptionMiddleware(env.SECRET_KEY);

📊 Event Bus

import {eventBus} from "stomp-react-hooks";

eventBus.on("connected", () => console.log("CONNECTED"));
eventBus.on("message", (msg) => console.log("MSG", msg));
eventBus.on("error", (err) => console.error("ERR", err));

📚 API Summary

| Hook | Purpose | |--------------------|-----------------------------------| | useStompClient() | Connect, send, subscribe | | useStompTopics() | Store and retrieve topic messages | | useStompStatus() | Reactively watch connection | | useStompReplay() | Replay last message | | useMiddleware | Register transformers | | registerSchema() | Register JSON schema for topic |


💼 Role-Based Access

Pass your user's role and optional attributes:

useStompClient({
    userRole: "admin",
    userAttributes: {team: "engineering"}
});

🛠 Project Structure

src/
├── hooks/
│   └── useStompClient.ts
│   └── useStompTopics.ts
│   └── ...
├── context/
│   └── StompContext.tsx
├── utils/
│   └── middleware.ts
│   └── offlineQueue.ts
│   └── ...

🤝 Contributing

We welcome PRs and issues! Fork this repo and run:

npm install
npm run build

📄 License

MIT © Bros Chign (https://github.com/jingx157)


📬 Contact

For support or questions:
📧 [email protected]
💬 GitHub Issues: https://github.com/jingx157/stomp-react-hooks/issues