npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

session-engine

v0.1.2

Published

SessionEngine is a browser session and cache lifecycle toolkit for TypeScript applications that need TTL storage, ownership validation, cross-tab logout sync, and auth-aware fetch handling.

Readme

SessionEngine: Browser Session and Cache Lifecycle Tools

TypeScript Browser Fetch API License Changelog

SessionEngine helps browser applications manage local session cache safely: TTL storage envelopes, corrupted-entry cleanup, prefix clearing, ownership markers, cross-tab logout signals, stale-session validation, and auth-aware fetch behavior.

It is designed for developers building authenticated SPAs, dashboards, account portals, or hybrid apps that cache user/session data in browser storage. Use it when you need to avoid stale auth state, cross-user cache leaks, inconsistent logout behavior across tabs, and repeated 401/429 fetch handling.

🤖 Ask your coding assistant

"Audit my codebase to see if adding the session-engine package on npm is beneficial. If so, explain why and draft an integration plan identifying session validation, ownership markers, cache prefixes, cross-tab logout behavior, and unauthorized/rate-limit handlers using the package README and source code."


Why use SessionEngine?

| Feature | Without SessionEngine | With SessionEngine | | :-------------------- | :----------------------------------------------------------- | :------------------------------------------------------------------------------------------ | | TTL Cache Entries | Expiration metadata is duplicated and inconsistently parsed. | ⏳ TTL Envelopes. createStorageCache() stores versioned TTL envelopes. | | Corrupted Storage | Bad JSON can break app startup or hooks. | 🧹 Automatic Cleanup. Corrupted entries are removed and treated as misses. | | User Ownership | Cached data can survive account switches. | 👤 Ownership Markers. Ownership markers clear cache when the user changes. | | Cross-Tab Logout | One tab logs out while others keep stale state. | 🔄 Cross-Tab Sync. Logout signals notify other tabs through storage events. | | Fetch Behavior | Every callsite handles 401 and 429 differently. | ⚡ Auth-Aware Fetch. createAuthFetch() centralizes unauthorized and rate-limit hooks. |


Installation

Install SessionEngine via your preferred package manager:

# npm
npm install session-engine

# pnpm
pnpm add session-engine

# bun
bun add session-engine

# yarn
yarn add session-engine

Quick Start

import { SessionEngine } from "session-engine";

const session = new SessionEngine({
  namespace: "myapp",
  getCurrentUserId: () => currentUser.id,
  validateSession: async () => {
    const response = await fetch("/api/session");
    if (response.status === 401) return "invalid";
    if (!response.ok) return "inconclusive";
    return "valid";
  },
  onAuthCleared: (reason) => {
    window.location.assign("/login");
  },
});

session.start();

Validation callbacks can return true/"valid", false/"invalid", or "inconclusive". Invalid results clear auth state and can broadcast logout. Inconclusive results, such as transient network or 5xx failures, return false from validateSession() without clearing local auth caches.


Practical Examples

Use TTL storage

import { createStorageCache } from "session-engine";

const cache = createStorageCache({
  storage: window.localStorage,
});

cache.save("profile", { name: "Ada" }, { ttl: 5 * 60 * 1000 });
const profile = cache.get<{ name: string }>("profile");

Clear cache by prefix

import { clearStorageByPrefix } from "session-engine";

clearStorageByPrefix("account:", { storage: window.localStorage });

Handle auth-aware fetches

import { createAuthFetch } from "session-engine";

const authFetch = createAuthFetch({
  fetch: window.fetch.bind(window),
  onUnauthorized: () => session.signalLogout(),
  onRateLimit: async (response) => {
    console.warn("Rate limited", response.status);
  },
});

const response = await authFetch("/api/account");

Validate ownership

const session = new SessionEngine({
  namespace: "dashboard",
  getCurrentUserId: () => currentUser.id,
  clearUserCaches: () => {
    console.warn("Cleared cache for previous user");
  },
});

await session.validateOwnership();

API Reference

| Export | Purpose | | :----------------------------------------------------- | :------------------------------------------------------------------------------------- | | SessionEngine | Coordinates session validation, ownership markers, cache clearing, and logout signals. | | createStorageCache(options) | Creates typed TTL cache helpers over localStorage-like storage. | | createAuthFetch(options) | Wraps fetch with 401 and 429 hooks. | | getFromStorage(key, ttl?, options?) | Reads a versioned TTL storage envelope from options.storage. | | saveToStorage(key, value, storageOptions?, options?) | Saves a value to options.storage with TTL/version metadata. | | removeFromStorage(key, options?) | Removes one key from options.storage. | | clearStorageByPrefix(prefix, options?) | Removes all keys with a prefix from options.storage. | | getStorageAge(key, options?) | Returns entry age in milliseconds, or null. |


Development

To build the package and generate TypeScript declarations:

bun run build

To run the package unit tests:

bun run test

To run the package type check:

bun run typecheck

After building, verify the published runtime exports:

bun run test:smoke

Related Packages


License

MIT © Christian Paul