Effective session management is crucial for maintaining security and providing a seamless user experience in applications using Capsule. This guide covers both client-side and server-side session management techniques.

Client-Side Session Management

Capsule uses sessions as a security measure when signing transactions. By default, a session is active for 90 minutes.

Checking Session Status

Before performing any action that requires an active session, such as signing a transaction, always check the session status:

const isLoggedIn = await capsule.isFullyLoggedIn();
if (!isLoggedIn) {
  await capsule.refreshSession();
}

Refreshing Sessions

Many SDK calls indicating user activity will automatically prolong the session. However, you can also extend the session programmatically:

const keepAliveIsSuccessful = await capsule.keepSessionAlive();

keepAliveIsSuccessful will be true if the keep-alive call was successful, and false otherwise.

Handling Session Timeouts

When a session times out, you’ll need to re-authenticate the user. Here’s an example of how to handle this in a transaction signing scenario:

try {
  await capsuleEthersSigner.signTransaction(transaction);
} catch (error) {
  if (error.message.includes('Session expired')) {
    await capsule.refreshSession();
    // Retry the transaction after refreshing the session
    await capsuleEthersSigner.signTransaction(transaction);
  } else {
    // Handle other errors
    console.error('Transaction signing failed:', error);
  }
}

Best Practices

  1. Regular Checks: Implement regular session checks in your application, especially before critical operations.

  2. Graceful Handling: Handle session expirations gracefully, providing a smooth re-authentication experience for users.

  3. Security First: When implementing server-side session management, always use secure channels for transmitting session data.

  4. Session Length: Consider your application’s security requirements when deciding on session length. You can customize this by contacting Capsule support.

Troubleshooting

If you encounter issues with session management:

  1. Ensure your Capsule SDK is up to date.
  2. Verify that your API key and environment settings are correct.
  3. Check your network connectivity, as session operations require communication with Capsule servers.
  4. If problems persist, review your logs and contact Capsule support with detailed information about the issue.