The core traffic to the NATS server will always be opaque byte arrays. The server does not process message payloads in any form. Therefore, you should alway encode data before sending data(Publish). On the receiving end(Subscribe), you decode accordingly.
JSONCodec().encode(s) / JSONCodec().decode(s)
;npm install nats.ws
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 = "chat.messages";
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) {
setMessages(prevMessages => [...prevMessages, new TextDecoder().decode(m.data)]);
}
} 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
const sendMessage = () => {
if (natsConnection) {
natsConnection.publish(subjectId, new TextEncoder().encode("New message from React!"));
}
};
return (
<div>
<button onClick={sendMessage}>Publish: Send NATS Message</button>
<div>
<h3>Subscribe: Messages received:</h3>
<ul>
{messages.map((msg, index) => (
<li key={index}>{msg}</li>
))}
</ul>
</div>
</div>
);
}