Send event to all subscribers

There are a few ways to send events to all subscribers. This example shows the recommended way of sending events to all subscribers.

What is a subscriber?

A subscriber in the following example is a user of your website currently using your website.

The recommended way of sending events to all subscribers is to publish an event to a topic and a channel. This way, you also get the benefit of event ordering.

Sending event and authorizing subscribers (Nodejs)

Sending global notifications

import { ExoquicPublisher } from "@exoquic/pub";
import * as exoquicAuth from "@exoquic/auth";

const apiKey = process.env.EXOQUIC_API_KEY;
const exoquicPublisher = new ExoquicPublisher({ apiKey });

app.post("/internalapi/send-notification", async (req, res) => {
	await exoquicPublisher.publish({
		topic: "notifications",
		channel: "global",
		payload: req.body.message,
	});

	res.status(200).send();
});

Authorizing subscriber for receiving global notifications

exoquicAuth.initSubscriptionAuthorizer({ apiKey });

app.get("/api/authorize-notification-subscribers", async (req, res) => {
	const subscriptionToken = await exoquicAuth.authorizeSubscription({
		topic: "notifications",
		channel: "global",
		resetFrom: "latest"
	});
	
	res.status(200).send(subscriptionToken);
});

Frontend code (React)


import { SubscriptionManager } from "@exoquic/sub";

const subscriptionManager = new SubscriptionManager(async () => {
  const response = await fetch("/api/authorize-notification-subscribers");
  return await response.text();
});

// React component example
const Notifications = () => {
	const [notifications, setNotifications] = useState([]);

	useEffect(() => {
		const subscriber = await subscriptionManager.subscribe(notifications => {
			setNotifications(currentNotifications => 
				[...currentNotifications, ...notificationBatch]
			);
		});

		return () => {
			subscriber.unsubscribe();
			setNotifications([]);
		};
	}, []);
	
	return (
		<div>
			<h1>Notifications</h1>
			{notifications.map((notification, index) => (
				<div key={index}>{notification.message}</div>
			))}
		</div>
	);
};