DEV Community

Cover image for Mark as Read, Everywhere
Violetta Soloveva
Violetta Soloveva

Posted on Originally published at violetsoloveva.substack.com

Mark as Read, Everywhere

Imagine you have the same app open in three tabs.

Tab A: the dashboard. Tab B: a report. Tab C: settings, opened twenty minutes ago and forgotten.

A notification comes in. You open it in tab A and read it. The red badge goes away.

You switch to tab B. Red badge. Tab C? Red badge.

The badge is very confident. It is also wrong.

The read was saved. The server knows. Every tab has its own idea of what you've read, and only one of them was there when it happened. The other two will find out on the next reload, which might be tomorrow.

It's a small thing that makes an app feel out of sync with itself. I fixed exactly this for notifications in an app I work on, with BroadcastChannel. Here's how it went, from ten lines to the version that shipped.

The full code, with tests, is in my pocket-patterns repo on GitHub if you'd rather read along.

1. What we were working with

Here's the setup:

  • Notifications arrive over SSE. The server pushes new notifications to each open tab through Server-Sent Events.
  • Reads are saved through an API call. When the user opens a notification, the client sends a "mark as read" request, and the server answers with the saved notifications.

"Doesn't SSE already do this?"

Sort of. SSE is how notifications get into a tab. Whether read status comes back out the same way depends on the server.

  • Our server only pushes new notifications. SSE in our app means "here's something new", not "here's everything that changed". A read is not news, so it never goes out.
  • Each tab holds its own state. Even if the server did push reads, every tab keeps its own list in memory. Tab A updated its list when the user clicked. Tabs B and C were never told.

Asking the backend to push read updates is a valid fix, and the only one that covers other devices. But tabs in the same browser can already talk to each other, at no server cost.

Why BroadcastChannel

There are a few ways for tabs to talk, and I compare all of them in the overview of every way tabs can talk. For this job, the short version:

  • The storage event works, but you have to write to localStorage to send a message. That turns a one-off event into stored state you then need to clean up.
  • A SharedWorker is a separate script with its own lifecycle. That's a lot of machinery for passing a list of IDs around.
  • BroadcastChannel does exactly one thing: any context on the same origin opens a channel by name, and messages posted there reach every other listener with that name.

Flow: the server pushes a notification over SSE to tab A, tab A saves the read through the API, the server confirms, and tab A broadcasts the read IDs over BroadcastChannel to tabs B and C

The server stays the source of truth for notifications. The channel only carries "these IDs are read now" between tabs.

SSE brings notifications into a tab, and BroadcastChannel tells the other tabs what happened to them.

2. The smallest version

Here's the core idea with plain BroadcastChannel:

Code from minimal.ts

Open a channel, listen, post. The whole API fits on a sticky note. The trouble starts when you try to ship the sticky note.

The catch: the sender doesn't receive its own message. The message goes to every other BroadcastChannel object with the same name. The one that posted it hears nothing.

BroadcastChannel works like a radio channel: tab A transmits, tabs B and C receive, and tab A doesn't hear its own transmission

So if tab A only updates its state when a message arrives, tab A never updates. The sender has to update itself.

Why not stop here? A real app has more going on than this snippet admits:

  • Who is this for? Sign out and back in as someone else, or switch workspaces, and you are still on the same channel.
  • When do we send? On click, or after the server agrees?
  • What if the order is off? A read can arrive before the notification it's about.
  • What about cleanup? Channels stay open until you close them, and callbacks can outlive the session they were made for.
  • What if the message is garbage? event.data is whatever someone posted.

Ten lines prove the idea, and the rest of the work is deciding who hears what and when.

3. What changes in a real app

The real version has three files: a channel wrapper, pure state functions, and a React hook that connects them.

The scope lives in the channel name

Notifications belong to a user in a workspace. Tabs of another user or another workspace must not hear about these reads.

You could put userId and workspaceId in every message and check them on arrival. Or you can make sure the wrong tabs never get the message at all:

Code from notificationReadChannel.ts

A different user or workspace means a different channel name, so the filtering happens before the message even exists. The payload is just { notificationIds }. The v1 leaves room to change the message format later without old and new tabs misreading each other.

Confirm first, update yourself, then publish

The tempting move is to broadcast on click. It feels faster. But if the request fails, the other tabs now think something is read that the server says isn't. The POST failed, but the gossip already spread.

So nothing goes out on click. The app calls confirmReadNotifications only after the "mark as read" request comes back, with the notifications the server returned. And because the sender never hears itself, the same function updates this tab before it tells the others:

Code from useNotificationReadSync.ts

Local state first, broadcast second. Only the IDs the server marked as read go out, so a click that fails to save never reaches other tabs. The receiving tabs update their state and don't publish anything, so a read never bounces between tabs.

readIds remembers reads that arrive early

Order matters too. Tab B opened a moment ago and its SSE stream hasn't delivered notification 7 yet. Tab A reads notification 7 and broadcasts it. Tab B hears "7 is read", but it has no notification 7 to mark.

If tab B drops the message, then a moment later the server sends notification 7 with whatever status it had when that payload was built. If that's isRead: false, the badge comes back. Like a horror movie villain, only smaller and red.

So the state keeps a set of confirmed read IDs next to the list:

Code from notificationState.ts

Every path into the state goes through this function, including incoming server data. A read only ever moves one way: once confirmed, later server data can update a notification's title, but it can't flip it back to unread.

A session guard ignores stale callbacks

Requests are slow, and users are fast. Say the user marks something as read and switches workspace before the response arrives. The response belongs to the old workspace. It shouldn't update the new workspace's list, and it definitely shouldn't publish on the new channel.

The hook keeps the current session in a ref and checks it on every call:

Code from useNotificationReadSync.ts

A callback created for the old scope compares its own scope to the session in the ref. After a workspace switch or a sign-out, they don't match, so the callback does nothing. The stored state is tagged with its scope too, so the new workspace starts from an empty list instead of inheriting the old one.

Messages are validated with Zod

Only pages from the same origin can post to a BroadcastChannel. So why validate?

Because "same origin" isn't the same as "same version of your code". A tab left open since last week's deploy still runs last week's code, and it posts to the same name. So does any other part of the app that opens a channel with that name by mistake. Validating costs a few lines:

Code from notificationReadChannel.ts

event.data is typed as unknown on purpose. Anything that doesn't match is ignored quietly.

Graceful fallback and cleanup

Sync between tabs is a nice extra. It should never break the tab you're in.

If BroadcastChannel doesn't exist, or its constructor throws, createNotificationReadChannel returns null, and the hook carries on with channel?.. Publishing is wrapped in try/catch for the same reason: by the time it runs, local state is already updated, and a failed broadcast shouldn't undo that.

The other half is closing the channel. An open channel keeps listening, and its callback keeps updating state for a workspace you left ten minutes ago. Very loyal. Very unhelpful. The effect opens one channel per scope and closes it in cleanup:

Code from useNotificationReadSync.ts

Cleanup runs on unmount and whenever the scope changes. A sign-out sets userId to null, so the old channel closes and no new one opens.

Every message has to be safe to receive late, twice, or from the wrong version of your app.

4. Testing it

jsdom implements a lot of the browser. BroadcastChannel is not in the lot.

A hand-written fake would mean testing the fake, including whether it remembered not to echo messages back to the sender. Node ships a real BroadcastChannel in worker_threads, so the tests import it and swap it in before each test with vi.stubGlobal('BroadcastChannel', NativeBroadcastChannel).

With a real channel, two tabs are just two renderHook calls. Each one opens its own channel with the same name, exactly like two browser tabs would:

Code from useNotificationReadSync.test.tsx

This one test covers several design choices at once:

  • The second tab gets the reads, and keeps its own titles, because only IDs travel.
  • Unconfirmed and unloaded items stay out. Notification 3 isn't read and was never loaded, so it isn't added to the first tab or published.
  • Nothing bounces. postMessage runs exactly once, so the receiving tab doesn't rebroadcast.
  • StrictMode is on. Effects run twice in development, so the channel opens, closes and opens again. The test still passes, which shows the cleanup holds up.

Delivery is asynchronous, so the test waits with waitFor instead of asserting right after act. The other tests in the file cover the remaining choices, from late notifications to a failing postMessage.

Test cross-tab code with a real channel and two hooks, so the test sees what the browser would.

5. Trade-offs and limitations

This pattern is small on purpose, and it has edges:

  • Closed tabs miss messages. BroadcastChannel doesn't queue anything. A closed tab won't hear about reads, and a tab that opens later starts from whatever the server sends.
  • It covers the same browser profile only. Tabs of the same origin in the same profile share channels. Another browser, another profile, or a private window is a different world.
  • It's not a replacement for server-pushed read status. If the user reads a notification on their phone, the laptop won't hear it through BroadcastChannel. Cross-device sync needs the server to push read status.

In our app the server still pushes only new notifications, so read status on other devices catches up on the next load. Tab sync fixed the case people actually notice, several tabs on one screen, without touching the backend.

BroadcastChannel keeps open tabs of one browser in sync, and anything wider still belongs to the server.

Conclusion

A red badge that won't go away is a small bug, and the fix is mostly a matter of deciding who should hear what:

  • Put the scope in the channel name. The wrong tabs never get the message, so the payload stays tiny.
  • Publish only server-confirmed reads. Other tabs should never learn something the server doesn't agree with.
  • Update the sender yourself. BroadcastChannel won't do it for you.
  • Remember reads that arrive early, so later server data can't undo them.
  • Guard against stale sessions, validate messages, and close the channel. Late and foreign messages should be harmless.
  • Test with a real channel. Node has one, and two renderHook calls make two tabs.

Full code: cross-tab-notification-sync on GitHub

Read it once, and it's read everywhere.

Top comments (0)