Skip to content

Repository files navigation

SessionEngine Banner

SessionEngine: Browser Session and Cache Lifecycle Tools

TypeScriptBrowserFetch APILicenseChangelog

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?

FeatureWithout SessionEngineWith SessionEngine
TTL Cache EntriesExpiration metadata is duplicated and inconsistently parsed.TTL Envelopes.createStorageCache() stores versioned TTL envelopes.
Corrupted StorageBad JSON can break app startup or hooks.🧹 Automatic Cleanup. Corrupted entries are removed and treated as misses.
User OwnershipCached data can survive account switches.👤 Ownership Markers. Ownership markers clear cache when the user changes.
Cross-Tab LogoutOne tab logs out while others keep stale state.🔄 Cross-Tab Sync. Logout signals notify other tabs through storage events.
Fetch BehaviorEvery 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";constsession=newSessionEngine({namespace: "myapp",getCurrentUserId: ()=>currentUser.id,validateSession: async()=>{constresponse=awaitfetch("/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";constcache=createStorageCache({storage: window.localStorage,});cache.save("profile",{name: "Ada"},{ttl: 5*60*1000});constprofile=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";constauthFetch=createAuthFetch({fetch: window.fetch.bind(window),onUnauthorized: ()=>session.signalLogout(),onRateLimit: async(response)=>{console.warn("Rate limited",response.status);},});constresponse=awaitauthFetch("/api/account");

Validate ownership

constsession=newSessionEngine({namespace: "dashboard",getCurrentUserId: ()=>currentUser.id,clearUserCaches: ()=>{console.warn("Cleared cache for previous user");},});awaitsession.validateOwnership();

API Reference

ExportPurpose
SessionEngineCoordinates 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

About

A browser session and cache lifecycle engine for TypeScript.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages