Para provides a comprehensive set of methods for managing authentication sessions in React Native applications. These sessions are crucial for secure transaction signing and other authenticated operations.

Session Duration

The Para session length is 2 hours by default, but can be configured to up to 30 days. To configure this parameter, please visit the Configuration section of the Developer Portal. A user signing a message or transaction extends the session by the duration of the session length.

Managing Sessions

Checking Session Status

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

async isSessionActive(): Promise<boolean>

In React Native applications, it’s especially important to check the session status before allowing users to access authenticated areas of your app due to the persistence of local storage between app launches.

Example usage:

import { para } from '../your-para-client';

async function checkSession() {
  try {
    const isActive = await para.isSessionActive();
    if (!isActive) {
      // First clear any existing data
      await para.logout();
      
      // Navigate to login screen
      navigation.navigate('Login');
    } else {
      // Session is valid, proceed with app flow
      navigation.navigate('Dashboard');
    }
  } catch (error) {
    console.error("Session check failed:", error);
    // Handle error
  }
}

Maintaining Active Sessions

Para provides the keepSessionAlive() method to extend an active session without requiring full reauthentication.

async keepSessionAlive(): Promise<boolean>

Example usage:

import { para } from '../your-para-client';

async function extendSession() {
  try {
    const success = await para.keepSessionAlive();
    if (!success) {
      // Session could not be extended
      // Clear storage and navigate to login
      await para.logout();
      navigation.navigate('Login');
    }
  } catch (error) {
    console.error("Session maintenance failed:", error);
  }
}

Refreshing Expired Sessions

When a session has expired, Para recommends initiating a full authentication flow rather than trying to refresh the session.

For React Native applications, always call logout() before reinitiating authentication when a session has expired to ensure all stored data is properly cleared.

import { para } from '../your-para-client';

async function handleSessionExpiration() {
  // When session expires, first clear storage
  await para.logout();
  
  // Then redirect to authentication screen
  navigation.navigate('Login');
}

Exporting Sessions to Your Server

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

exportSession({ excludeSigners?: boolean }): string

If your server doesn’t need to perform signing operations, use { excludeSigners: true } when exporting sessions for enhanced security.

Example implementation:

import { para } from '../your-para-client';

async function sendSessionToServer() {
  // Export session without signing capabilities
  const sessionData = para.exportSession({ excludeSigners: true });
  
  // Send to your server
  try {
    const response = await fetch('https://your-api.com/sessions', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ session: sessionData }),
    });
    
    if (!response.ok) {
      throw new Error('Failed to send session to server');
    }
    
    return await response.json();
  } catch (error) {
    console.error('Error sending session to server:', error);
    throw error;
  }
}

Best Practices for React Native

  1. Check Sessions on App Launch: Verify session status when your app starts to determine if users need to reauthenticate.
// In your app's entry point or navigation setup
useEffect(() => {
  async function checkSessionOnLaunch() {
    const isActive = await para.isSessionActive();
    if (isActive) {
      navigation.navigate('Dashboard');
    } else {
      await para.logout(); // Clear any lingering data
      navigation.navigate('Login');
    }
  }
  
  checkSessionOnLaunch();
}, []);
  1. Implement Automatic Session Extension: For long app usage sessions, periodically call keepSessionAlive() to prevent unexpected session expirations.
useEffect(() => {
  const sessionInterval = setInterval(async () => {
    try {
      const isActive = await para.isSessionActive();
      if (isActive) {
        await para.keepSessionAlive();
      } else {
        // Session expired, handle accordingly
        await para.logout();
        navigation.navigate('Login');
      }
    } catch (error) {
      console.error('Error maintaining session:', error);
    }
  }, 30 * 60 * 1000); // Check every 30 minutes
  
  return () => clearInterval(sessionInterval);
}, []);
  1. Handle Background/Foreground State: React Native apps can be backgrounded and foregrounded, which may affect session status.
import { AppState } from 'react-native';

useEffect(() => {
  const subscription = AppState.addEventListener('change', async (nextAppState) => {
    if (nextAppState === 'active') {
      // App came to foreground, check session
      const isActive = await para.isSessionActive();
      if (!isActive) {
        await para.logout();
        navigation.navigate('Login');
      }
    }
  });
  
  return () => {
    subscription.remove();
  };
}, []);
  1. Secure Storage Configuration: For enhanced security, consider implementing a custom storage solution to manage sensitive session data.

Next Steps:

Explore more advanced features and integrations with Para in Flutter: