Skip to main content

Notifications

A notification bell like the one in most web apps. A Hono server in the same Vite project sends a new notification every few seconds. The bell, the list and the tab title show the unread count, a click marks one as read, and the list keeps only the ten newest.

intermediateuseListenerrealtimecacheserver
import { Hono } from "hono";
import { streamSSE } from "hono/streaming";

export type Notification = { id: number; title: string; body: string; read: boolean; createdAt: string };

const templates = [
{ title: "New comment", body: "Ada replied to your post." },
{ title: "Build passed", body: "main is green again." },
{ title: "Mention", body: "Linus mentioned you in #general." },
{ title: "Invoice paid", body: "Invoice #1042 was paid." },
{ title: "New follower", body: "Grace started following you." },
{ title: "Deploy finished", body: "Version 2.4.0 is live." },
];

// In memory, so the data resets when the dev server restarts.
let nextId = 1;
let notifications: Notification[] = [];

const create = () => {
const template = templates[Math.floor(Math.random() * templates.length)];
const notification: Notification = { id: nextId++, ...template, read: false, createdAt: new Date().toISOString() };
notifications = [notification, ...notifications].slice(0, 50);
return notification;
};

// Two to start with.
create();
create();

// ---------- Push ----------

const subscribers = new Set<(notification: Notification) => void>();
let timer: ReturnType<typeof setTimeout> | undefined;

// A new notification every 2 to 6 seconds while at least one tab listens.
const scheduleNext = () => {
timer = setTimeout(
() => {
const notification = create();
subscribers.forEach((send) => send(notification));
scheduleNext();
},
2000 + Math.random() * 4000,
);
};

const app = new Hono()
.basePath("/api")
.get("/notifications", (c) => c.json(notifications.slice(0, 10)))
.post("/notifications/:id/read", (c) => {
const notification = notifications.find((item) => item.id === Number(c.req.param("id")));
if (!notification) return c.json({ message: "No such notification" }, 404);
notification.read = true;
return c.json(notification);
})
.post("/notifications/read-all", (c) => {
notifications.forEach((item) => {
item.read = true;
});
return c.json({ ok: true });
})
// Each new notification is sent as a named event, `event: notification`.
.get("/events", (c) =>
streamSSE(c, async (stream) => {
const send = (notification: Notification) =>
void stream.writeSSE({ event: "notification", data: JSON.stringify(notification) });
subscribers.add(send);
if (!timer) scheduleNext();

stream.onAbort(() => {
subscribers.delete(send);
if (subscribers.size === 0) {
clearTimeout(timer);
timer = undefined;
}
});

// Keep the response open. A comment line every 15 s keeps proxies from closing an idle stream.
while (!stream.aborted) {
await stream.sleep(15000);
await stream.write(": ping\n\n");
}
}),
);

// `@hono/vite-dev-server` serves the default export inside the Vite dev server.
export default app;
Run locallynpx tiged BetterTyped/hyper-fetch/examples/react/notifications hyper-fetch-react-notifications && cd hyper-fetch-react-notifications && npm install && npm run dev
What it shows
  1. useListener receives the notification events of a server-sent events stream.
  2. One cached list holds the notifications. Pushed events, reads and the first load all write to it.
  3. Derived state: the unread count is computed from the list, so the badge and the tab title never disagree with it.
  4. A capped list: every write keeps the ten newest entries.
  5. Mark as read changes the list at once and puts it back if the server refuses.

How it works​

  1. server/app.ts keeps notifications in memory and creates a new one every 2 to 6 seconds while a tab listens. GET /api/events sends each as a named event, event: notification.

  2. api.ts defines the HTTP requests and onNotification, a listener on the notification topic of a ServerSentEventsAdapter socket.

  3. updateNotifications(change) is the only way the list changes. It runs client.cache.update(getNotifications, ...) and cuts the result to MAX_NOTIFICATIONS:

    cached?.data ? { data: change(cached.data).slice(0, MAX_NOTIFICATIONS) } : {},
  4. useNotifications loads the list with useFetch(getNotifications) and adds each pushed notification on top with onEvent. The unread count is derived from the cached list on every render.

  5. read marks a notification as read in the cache first, then sends POST /api/notifications/:id/read. send() resolves with error instead of throwing, and an error puts the unread state back. Mark all as read works the same way, and loads the list again on failure.

  6. A useEffect writes the count to document.title, so it shows in the browser tab.

When to use it
  • Notification bells, inboxes and activity feeds.
  • Any list that grows from pushed events and must not grow without limit.
  • Counters, badges and titles that must match the data they count.

Summary

A server-sent events listener puts each new notification into one cached list, which every write cuts to the newest ten. The badge, the list and the tab title all read that list, and mark as read updates it before the server answers.