Overview

Capsule provides a comprehensive set of methods for managing authentication sessions. These sessions are crucial for secure transaction signing and other authenticated operations. Proper session management helps maintain security while ensuring a seamless user experience.

Checking Session Status

Use isSessionActive() to verify whether a user’s session is currently valid before performing authenticated operations.

async isSessionActive(): Promise<boolean>

This method returns a boolean indicating if the session is currently valid and active. For external wallet connections, this will always return true.

Example usage:

const capsule = new Capsule(env, apiKey);

try {
  const isActive = await capsule.isSessionActive();
  if (!isActive) {
    // Handle expired session
    await capsule.refreshSession(true);
  }
} catch (error) {
  console.error("Session check failed:", error);
}

Maintaining Active Sessions

Use keepSessionAlive() to extend an active session’s validity without requiring full reauthentication.

async keepSessionAlive(): Promise<boolean>

This is a lightweight method that attempts to maintain the current session and returns a boolean indicating success or failure.

Example usage:

const capsule = new Capsule(env, apiKey);

try {
  const success = await capsule.keepSessionAlive();
  if (!success) {
    // Handle failed session maintenance
    await capsule.refreshSession(true);
  }
} catch (error) {
  console.error("Session maintenance failed:", error);
}

Refreshing Expired Sessions

Use refreshSession() when a session has fully expired and needs to be reestablished through user authentication.

async refreshSession(shouldOpenPopup: boolean): Promise<string>

When shouldOpenPopup is true, this method automatically opens an authentication window. Otherwise, it returns a URL that should be opened in a popup for user authentication. After calling refreshSession(), you must use waitForLoginAndSetup() to wait for the authentication to complete.

async waitForLoginAndSetup(
  loginWindow?: Window,
  skipSessionRefresh?: boolean
): Promise<{
  isComplete: boolean;
  isError?: boolean;
  needsWallet?: boolean;
  partnerId?: string;
}>

Pass the popup window reference to waitForLoginAndSetup() when handling popups manually. This enables automatic error detection if the user closes the popup.

Example usage:

const capsule = new Capsule(env, apiKey);

// Automatic popup handling
try {
  await capsule.refreshSession(true);
  // Wait for authentication to complete
  const { isComplete, isError } = await capsule.waitForLoginAndSetup();
  if (!isComplete || isError) {
    throw new Error("Session refresh failed");
  }
} catch (error) {
  console.error("Session refresh failed:", error);
}

// Manual popup handling
try {
  const authUrl = await capsule.refreshSession(false);
  const popup = window.open(authUrl, "Auth", "width=400,height=600");
  // Wait for authentication to complete
  const { isComplete, isError } = await capsule.waitForLoginAndSetup(popup);
  if (!isComplete || isError) {
    throw new Error("Session refresh failed");
  }
} catch (error) {
  console.error("Failed to refresh session:", error);
}

Client-Server Session Transfer

Exporting Sessions

Use exportSession() when you need to transfer session state to a server for performing operations on behalf of the user.

exportSession(): string

Returns a Base64 encoded string containing the session state, including user details, wallet information, and authentication data.

Example client-side export:

const capsule = new Capsule(env, apiKey);

// After user authentication
const serializedSession = capsule.exportSession();

// Send to server
await fetch("/api/store-session", {
  method: "POST",
  body: JSON.stringify({ session: serializedSession }),
  headers: { "Content-Type": "application/json" },
});

Importing Sessions

Use importSession() on your server to restore a previously exported session state.

async importSession(serializedInstanceBase64: string): Promise<void>
Takes a Base64 encoded session string from exportSession() and restores the complete session state.

Example server-side implementation:

const capsule = new Capsule(env, apiKey);

app.post("/api/server-action", async (req, res) => {
  try {
    await capsule.importSession(req.body.session);

    const isActive = await capsule.isSessionActive();
    if (!isActive) {
      return res.status(401).json({ error: "Session expired" });
    }

    // Perform authenticated operations
    const walletId = capsule.currentWalletIdsArray[0]?.[0];
    const signature = await capsule.signMessage(walletId, messageToSign);

    res.json({ signature });
  } catch (error) {
    res.status(500).json({ error: "Server operation failed" });
  }
});