HelloJohn / docs
SDKsJavaScript SDK

Session Management

Manage sessions with the HelloJohn JavaScript SDK — get current session, access tokens, refresh, and storage configuration.

Session Management

The session namespace provides access to the current session and token management in the @hellojohn/js SDK.


Get Current Session

import { HelloJohn } from "@hellojohn/js";

const hj = new HelloJohn({ tenantId: "tnt_01HABCDEF654321" });

const session = await hj.session.getSession();

if (session) {
  console.log("Access token:", session.accessToken);
  console.log("User ID:", session.userId);
  console.log("Expires at:", session.expiresAt);
} else {
  console.log("Not authenticated");
}

Session Object

interface Session {
  id: string;
  userId: string;
  accessToken: string;    // Use this as Bearer token for API calls
  expiresAt: Date;
  refreshExpiresAt: Date;
}

Get Access Token

Get the access token for making authenticated API calls:

const token = await hj.session.getAccessToken();

if (token) {
  const res = await fetch("/api/data", {
    headers: { Authorization: `Bearer ${token}` },
  });
}

getAccessToken() automatically refreshes the token if it's about to expire.


Refresh Token

Manually trigger a token refresh:

await hj.session.refresh();

The SDK refreshes automatically — manual refresh is only needed in specific cases (e.g., after server-side permission changes).


Storage Configuration

By default, sessions are stored in localStorage. Customize storage for security or SSR:

const hj = new HelloJohn({
  tenantId: "tnt_01HABCDEF654321",
  storage: {
    // Use sessionStorage (cleared when tab closes)
    getItem: (key) => sessionStorage.getItem(key),
    setItem: (key, value) => sessionStorage.setItem(key, value),
    removeItem: (key) => sessionStorage.removeItem(key),
  },
});

Custom in-memory storage (for SSR or testing):

const memStorage = new Map<string, string>();

const hj = new HelloJohn({
  tenantId: "tnt_01HABCDEF654321",
  storage: {
    getItem: (key) => memStorage.get(key) ?? null,
    setItem: (key, val) => memStorage.set(key, val),
    removeItem: (key) => memStorage.delete(key),
  },
});

Server-Side Session Retrieval

When tokens arrive via URL parameters (after OAuth or magic link):

// Called on the callback page
await hj.session.exchangeCodeForSession(window.location.href);

// Now getSession() returns the active session
const session = await hj.session.getSession();

Session Events

Listen for session changes:

hj.session.onSessionChange((session) => {
  if (session) {
    updateUI("authenticated", session.userId);
  } else {
    updateUI("unauthenticated");
  }
});

On this page