The main idea is to subscribe to all subjects using the wildcard(>
).
You will see all messages from all subjects that are going through your nats server and check
for the message meta data(subject). This is not efficient but it is the only way
that I know right now without enabling JetStream. There must be a better way to get meta info from
the server itself.
npm install nats.ws
Live demo - List all subjects on your nats server
import React, { useState, useEffect } from 'react';
import { connect } from 'nats.ws';
export default function WssSubPub() {
const [natsConnection, setNatsConnection] = useState(null);
const [messages, setMessages] = useState([]);
const subjectId = ">";
useEffect(() => {
async function setupNATS() {
try {
const nc = await connect({ servers: ["wss://rollingweddingpictures.com"] });
setNatsConnection(nc);
const sub = nc.subscribe(subjectId);
for await (const m of sub) {
console.log({m});
const msg = `subject = ${m.subject} ⟶ msg = ${new TextDecoder().decode(m.data)}`;
setMessages(prevMessages => [...prevMessages, msg]);
}
} catch (error) {
console.error("NATS connection error:", error);
}
}
setupNATS();
// https://stackoverflow.com/questions/56800694/what-is-the-expected-return-of-useeffect-used-for
return () => {
if (natsConnection) {
natsConnection.close(); // Clean up connection on unmount
}
};
}, []); // Run once on mount
return (
<div>
<div>
<h3>Subscribe to > to view all messages from all subjects: They are:</h3>
<ul>
{messages.map((msg, index) => (
<li key={index}>{msg}</li>
))}
</ul>
</div>
</div>
);
}