Skip to content

Repository files navigation

Shared Session for JavaScript

A lightweight, zero-dependency Proxy wrapper around sessionStorage that automatically synchronizes namespaced entries across same-origin browser tabs, windows, and iframes using the BroadcastChannel API.

Features

  • Drop-in Storage API: Supports standard methods (getItem, setItem, removeItem, clear, key, length) as well as direct property access (store.foo = "bar", delete store.foo, Object.keys(store)).
  • Namespace Isolation: Prefixes keys internally so multiple instances or regular sessionStorage entries never collide.
  • Async Hydration (store.ready): Automatically requests existing state from already-open tabs upon creation and resolves when synced.
  • Custom Broadcast Listeners. Attach event listeners to respond to updates from other document instances.
  • Lifecycle Control: Includes .close() to disconnect a tab's channel and .destroy() to wipe shared state across all open tabs.
  • TypeScript Ready: Includes full .d.ts type definitions.

Quick Start

import SharedSession from "js-shared-session";
// Create or retrieve a namespaced instance (defaults to "shared")
// Optional method as second function to listen for changes posted
const store = SharedSession("myApp", (event) => {
  console.log("Synced from another tab:", event.data);
});
// Wait for initial state sync from any existing open tabs
await store.ready;
// Standard Storage methods or direct property assignment both sync across tabs
store.setItem("theme", "dark");
store.username = "AtomicNoggin";
console.log(store.getItem("theme")); // "dark"
console.log(Object.keys(store)); // ["theme", "username"]

API Reference

SharedSession(namespace?, listener?)

Creates (or returns an existing) Proxy-wrapped sessionStorage instance for namespace.

  • namespace (string, optional): Defaults to "shared". Must match across tabs to sync.
  • listener (function, optional): Callback receiving MessageEvent objects (init_response, setItem, removeItem, clear) from other tabs. The listener receives a MessageEvent whose event.data is a SharedSessionMessage.

SharedSessionMessage Structure

interface SharedSessionMessage {
  // name of the event
  name: "init_request" | "init_response" | "setItem"
      | "removeItem"  | "clear";
  // session storage key that changed, or null for init_request, init_response, & clear
  key: string | null;
  // new value for setItem, set of key: value pairs for init_response, or null otherwise
  newValue: string | Record<string, string> | null;
  // previous value, if any, for setItem & removeItem, or null otherwise
  oldValue: string | null;
}

Instance Properties & Methods

  • store.ready: Promise that resolves once existing tab state has hydrated (or after a 100ms timeout if no other tabs are open).
  • store.close(): Clears listeners, closes the underlying BroadcastChannel, and removes the namespace from the internal registry without deleting stored data.
  • store.destroy(): Deletes all keys in the namespace, broadcasts a "clear" event to other open tabs, and calls store.close().

Static Listener Helpers

Optionally add and remove secondary MessageEvent listeners as required.

  • SharedSession.addBroadcastListener(namespace?, listener): Attaches an additional listener to an active namespace. Returns true if the namespace exists.
  • SharedSession.removeBroadcastListener(namespace?, listener): Detaches a previously registered listener.

Use these helpers to react to cross-tab sync events without holding a reference to the proxy instance. Both accept an optional namespace (defaults to "shared" when omitted) and require a listener function.

Note: the helpers act on the namespace within the current tab, so a SharedSession for that namespace must already exist here first. If it does not, addBroadcastListener returns false (it does not throw).

import SharedSession from "js-shared-session";

// A SharedSession for "myApp" must exist before adding another listener to it.
const store = SharedSession("myApp");
await store.ready;

// Named handler so it can be removed later.
function onSync(event) {
  const { name, key, newValue, oldValue } = event.data;
  // name is one of: "init_response", "setItem", "removeItem", "clear"
  if (name === "setItem") {
    console.log(`"${key}" updated elsewhere: ${oldValue} -> ${newValue}`);
  }
}

// Attach the listener. Returns true because the "myApp" namespace is active.
const attached = SharedSession.addBroadcastListener("myApp", onSync); // true

// Now any setItem/removeItem/clear from OTHER tabs fires onSync in this tab.

// Detach when finished. Returns true if the listener was registered.
SharedSession.removeBroadcastListener("myApp", onSync); // true

Default namespace. Pass the function as the first argument to target the default "shared" namespace:

SharedSession(); // creates/gets the default "shared" instance

const ok = SharedSession.addBroadcastListener((event) => {
  console.log("shared namespace changed:", event.data);
});

Namespace not yet created. Without an active instance in this tab the helper returns false instead of throwing:

const attached = SharedSession.addBroadcastListener("cart", () => {}); // false
if (!attached) {
  console.warn('Create SharedSession("cart") before attaching a listener.');
}

Security Notes

  • Data stays strictly in sessionStorage and in-memory BroadcastChannel messages (never written to localStorage or cookies).
  • Restricted by browser same-origin policy, though any script running on the same origin can read or broadcast to the channel—avoid storing high-privilege secrets if untrusted third-party scripts run on your page.

Releases

Packages

Contributors

Languages