Skip to content

Package overview

Observe browser state. Derive session intelligence. React with confidence.

Browser Lifecycle (@jayoncode/browser-lifecycle) normalizes browser session signals into one session, one snapshot, and one event stream — with optional session intelligence and DX on top.

One session. One snapshot. One event stream.
Everything else is derived.

Observe → Understand → React

text
Browser APIs

Normalized Session

Session Intelligence (opt-in)

Developer APIs (opt-in)
Most librariesBrowser Lifecycle
Browser APIs → EventsBrowser APIs → Normalized Session → Session Intelligence → Developer APIs
PillarMeaning
ObserveNormalize browser lifecycle into one consistent API
UnderstandTransform signals into meaningful session insights
ReactBuild resilient apps with Wait, Conditions, Resilience, plugins

Five capabilities

CardDistinction
Unified Browser LifecycleFoundation — visibility, focus, connectivity, idle, page lifecycle, cross-tab
Session IntelligenceCurrent derived state — activity + page-local presence
TimelineChronological session event history
Session InsightsAggregates — metrics + reports (not an analytics SDK)
Developer ExperienceHow you react — Wait, Conditions, Resilience, plugins, playground

When to use

  • Pause media/polling when the tab hides; resume on visible
  • Idle / session-timeout UX, connectivity-aware sync, cross-tab leadership
  • One shared session instead of scattered document / window listeners
  • Opt-in timeline, metrics, or wait helpers when you need them

When not to use

  • You only need a one-off visibilitychange in a tiny page (raw API may be enough)
  • Server-only Node services with no browser globals — create the session in the client bootstrap
  • Product analytics / telemetry SDKs — this is session understanding, not an analytics product
  • Multi-user presence — presence here is page-local (this browser session)

Features

  • Visibility, focus, connectivity, idle, page lifecycle, and cross-tab behind one session
  • Typed on() / subscribe() events + readonly getSnapshot()
  • SSR-safe capability detection before modules attach
  • Plugins and opt-in intelligence / DX factories (zero-cost until you ask)

Zero-cost until you ask

Core observation stays lightweight. Session intelligence and developer experience allocate only after you call their factories.

ts
import { createBrowserLifecycle, createTimelineApi } from "@jayoncode/browser-lifecycle";

const lifecycle = createBrowserLifecycle({ autoStart: true });
// lean core only

const timeline = createTimelineApi(lifecycle);
// cost starts here

Single entrypoint

Everything imports from @jayoncode/browser-lifecycle (no feature subpaths). Tree-shaking still applies to unused exports.

Install

bash
npm install @jayoncode/browser-lifecycle
bash
pnpm add @jayoncode/browser-lifecycle
bash
yarn add @jayoncode/browser-lifecycle

Example: pause work when the tab is hidden

ts
import { createBrowserLifecycle } from "@jayoncode/browser-lifecycle";

const lifecycle = createBrowserLifecycle({ autoStart: true });

lifecycle.on("page:hidden", () => {
  pauseMedia();
  flushTelemetry();
});

lifecycle.on("page:visible", () => {
  resumeMedia();
});

// Form Intelligence composition (optional peer): save drafts when the tab hides —
// see [FI Patterns → Draft on tab hide](/packages/form-intelligence/modules/patterns#composition-draft-on-tab-hide-browser-lifecycle).

const { visibility, attention, connectivity } = lifecycle.getSnapshot();

// Sync teardown — disposed sessions must not be reused
lifecycle.dispose();

One instance per tab replaces scattered document / window listeners with typed events and a readonly snapshot.

Verify event ordering →

Problem → approach

Typical painBrowser Lifecycle
document, window, and navigator listeners scattered across featuresOne createBrowserLifecycle() session with typed on() handlers
Tab visibility, focus, and connectivity each wired differentlyModules normalize signals; getSnapshot() exposes consolidated state
SSR crashes or silent no-ops when APIs are missingCapability detection and SSR-safe defaults before modules attach

Overview

createBrowserLifecycle() orchestrates browser signals through a module pipeline. Consumers subscribe to events or poll getSnapshot(); modules compose behind a single session boundary.

ConcernAPI surface
Lifecyclestart(), stop(), dispose(), phase events
Signalson(event, handler), once(), subscribe() for the full feed
StategetSnapshot() — readonly session state
ExtensionPlugin hooks (onEvent on plugins), module configuration
DiagnosticsgetRuntimeDiagnostics() for development

Designed for SSR-safe capability detection and framework-agnostic integration (React, Vue, vanilla, etc.).

Always dispose

Call lifecycle.dispose() on route unmount or app shutdown (dispose is synchronous). Disposed sessions must not be reused — create a new instance.

SSR

Construct and start() only in the browser (or after hydration). Capability detection avoids crashing when document / window are missing; listeners still need a client environment.

Documentation path

Foundation

#GuideTopicsPlayground
1TutorialInstall, session, subscribe, disposeSandbox
2Core conceptsSession, snapshot, events, modulesSandbox / State

Core modules (Observe)

#GuideTopicsPlayground
3VisibilityPage Visibility APIVisibility
4FocusWindow focus / blurFocus
5IdleActivity + idle timeoutIdle
6ConnectivityAdvisory online/offlineConnectivity
7Cross-tabLeader election, tab messagesCross Tab
8Page lifecycleSuspend / resume / restoreLifecycle
9EventsSubscription modelEvents
10Session corePhases, startup orderLifecycle

Configuration and extension

#GuideTopicsPlayground
11PluginsHooks, priority, diagnosticsPlugins
12Core infrastructureConfig, capabilities, SSRConfiguration
13Usage guideProduction patternsDeveloper tools

Understand & React (opt-in)

#GuideTopics
14Intelligence overviewObserve → Understand → React; factories
15Activity / PresenceSession Intelligence (current derived state)
16TimelineChronological history
17Metrics / ReportsSession Insights (aggregates)
18Wait / Conditions / ResilienceDeveloper Experience
19Framework adaptersReact, Vue, Svelte, Solid, Angular

Package fit

RequirementModule / event
Pause background work on tab hidepage:hidden / page:visible
React to window focuswindow:focus / window:blur
Offline-aware UIconnection:* (advisory)
Idle timeout / autosave triggersIdle module
Session duration / attentionMetrics (Session Insights)
Event audit logTimeline
Reconnect / wake / restoreResilience
React / Vue / etc. bindingsAdapters
Cross-tab coordinationCross-tab
Cross-cutting observationPlugins
SSR / capability guardsCore infrastructure

Reference

ResourceLink
API (TypeDoc)/packages/browser-lifecycle/api/
Framework adapters/packages/browser-lifecycle/modules/adapters
Framework examples/packages/browser-lifecycle/examples/
Best practices/packages/browser-lifecycle/best-practices/
Patterns/packages/browser-lifecycle/patterns/
FAQ/packages/browser-lifecycle/faq/
Playground guide/packages/browser-lifecycle/playground/playground
Draft DeskOfficial reference app — online/offline & session signals in a live form flow

Version

Current npm version: v0.3.3 (@jayoncode/browser-lifecycle). See Migration and Changelog for release history.

An ecosystem of independent, headless TypeScript libraries engineered for modern web development. Every package includes interactive playgrounds and documentation that evolves alongside the code.