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

@toruslabs/session-manager

v5.6.0

Published

session manager web

Readme

Web Session Manager

Introduction

This package supports web SDK session flows with two modules:

  1. Storage Manager -- legacy encrypted metadata storage with a server-backed hex session ID.
  2. Auth Session Manager -- token-based sessions with automatic refresh, cross-tab synchronization, and an authenticated HTTP client.

Installation

npm install @toruslabs/session-manager

Storage Manager

StorageManager is the legacy encrypted metadata session flow. It creates, authorizes, updates, and invalidates server-backed sessions using a hex session ID.

import { StorageManager } from "@toruslabs/session-manager";

const storage = new StorageManager({
  sessionId: StorageManager.generateRandomSessionKey(),
  sessionNamespace: "my-app",
});

await storage.createSession({ userId: "123" });
const sessionData = await storage.authorizeSession();

Auth Session Manager

AuthSessionManager handles the full lifecycle of access tokens, refresh tokens, and session data. It stores tokens in configurable storage backends, refreshes them automatically, and deduplicates concurrent refresh calls -- including across browser tabs via the Web Locks API.

Setup

import { AuthSessionManager, HttpClient } from "@toruslabs/session-manager";

const session = new AuthSessionManager({
  apiClientConfig: {
    baseURL: "https://auth.example.com",
    // optional: override default endpoints
    sessionsEndpoint: "/v1/auth/session",
    logoutEndpoint: "/v1/auth/logout",
  },
});

Storing Tokens

After login (e.g. from an auth iframe postMessage), store the full token set:

await session.setTokens({
  session_id: "...",
  access_token: "...",
  refresh_token: "...",
  id_token: "...",
});

Restoring a Session

On page load, call authorize() to refresh tokens and retrieve the encrypted session data:

const sessionData = await session.authorize();

if (sessionData) {
  // Session restored -- sessionData contains the decrypted payload
  console.log(session.isAuthenticated()); // true
} else {
  // No valid session -- redirect to login
}

Reading Tokens

const accessToken = await session.getAccessToken();
const refreshToken = await session.getRefreshToken();
const idToken = await session.getIdToken();
const sessionId = await session.getSessionId();

Logout

Calls the logout endpoint with the current tokens, then clears all stored data:

await session.logout();

Custom Storage

By default, tokens are stored in localStorage (access token, session ID, ID token) and cookies (refresh token). You can override any or all of these:

import {
  AuthSessionManager,
  MemoryStorage,
  SessionStorageAdapter,
  CookieStorage,
} from "@toruslabs/session-manager";

const session = new AuthSessionManager({
  apiClientConfig: { baseURL: "https://auth.example.com" },
  storage: {
    accessToken: new SessionStorageAdapter(),
    refreshToken: new CookieStorage({ secure: true, sameSite: "Lax" }),
    sessionId: new MemoryStorage(),
    // idToken falls back to localStorage
  },
  storageKeyPrefix: "myapp", // default: "w3a"
});

You can also implement the IStorageAdapter interface for custom backends (e.g. IndexedDB, a remote store):

import type { IStorageAdapter } from "@toruslabs/session-manager";

class IndexedDBStorage implements IStorageAdapter {
  async get(key: string): Promise<string | null> { /* ... */ }
  async set(key: string, value: string): Promise<void> { /* ... */ }
  async remove(key: string): Promise<void> { /* ... */ }
}

Access Token Provider

If you manage access tokens externally (e.g. from a parent SDK), provide a callback instead of relying on stored tokens:

const session = new AuthSessionManager({
  apiClientConfig: { baseURL: "https://auth.example.com" },
  accessTokenProvider: async () => {
    return await parentSdk.getAccessToken();
  },
});

HttpClient

HttpClient wraps @toruslabs/http-helpers with automatic authorization and transparent 401 retry. It pairs with AuthSessionManager to attach Bearer tokens and refresh them when they expire.

Setup

import { AuthSessionManager, HttpClient } from "@toruslabs/session-manager";

const session = new AuthSessionManager({
  apiClientConfig: { baseURL: "https://auth.example.com" },
});

const http = new HttpClient(session);

Authenticated Requests

Pass authenticated: true to attach the access token and enable automatic 401 retry:

// GET
const users = await http.get<User[]>("https://api.example.com/users", {
  authenticated: true,
});

// POST
const newUser = await http.post<User>(
  "https://api.example.com/users",
  { name: "Alice" },
  { authenticated: true }
);

// PUT, PATCH, DELETE work the same way
await http.put("https://api.example.com/users/1", data, { authenticated: true });
await http.patch("https://api.example.com/users/1", data, { authenticated: true });
await http.delete("https://api.example.com/users/1", {}, { authenticated: true });

Unauthenticated Requests

Omit authenticated (or set it to false) for public endpoints -- no token is attached and 401s are not retried:

const health = await http.get("https://api.example.com/health");

401 Handling

When an authenticated request receives a 401:

  1. HttpClient triggers a token refresh via session.handleUnauthorized().
  2. Concurrent 401s are deduplicated -- only one refresh call is made.
  3. New requests that arrive during the refresh wait for it to complete before sending.
  4. The failed request is retried once with the new access token.

Custom Headers and Options

const result = await http.get("https://api.example.com/resource", {
  authenticated: true,
  headers: { "X-Custom-Header": "value" },
  timeout: 5000,
  useAPIKey: true,
});

Development

Setup

git clone https://github.com/torusresearch/session-manager-web.git
cd session-manager-web
npm i

Bundling

Each sub package is distributed in 2 formats:

  • lib.esm build dist/lib.esm/index.js in es6 format
  • lib.cjs build dist/lib.cjs/index.js in es5 format

By default, the appropriate format is used for your specified usecase. You can use a different format (if you know what you're doing) by referencing the correct file.

The cjs build is not polyfilled with core-js. It is up to the user to polyfill based on the browserlist they target.

Build

Ensure you have a Node.JS development environment setup:

npm run build

Requirements

  • This package requires a peer dependency of @babel/runtime
  • Node 20+