> ## Documentation Index
> Fetch the complete documentation index at: https://docs.getpara.com/llms.txt
> Use this file to discover all available pages before exploring further.

# React Native Session Management

> Guide to managing authentication sessions in Para for React Native applications

export const Link = ({href, label, newTab = false}) => {
  const [isHovered, setIsHovered] = useState(false);
  return <a href={href} target={newTab ? '_blank' : '_self'} rel={newTab ? 'noopener noreferrer' : undefined} className="not-prose inline-block relative text-black font-semibold cursor-pointer border-b-0 no-underline" onMouseEnter={() => setIsHovered(true)} onMouseLeave={() => setIsHovered(false)}>
      {label}
      <span className={`absolute left-0 bottom-0 w-full rounded-sm bg-gradient-to-r from-orange-600 to-purple-600 transition-all duration-300 ${isHovered ? 'h-0.5' : 'h-px'}`} />
    </a>;
};

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

Para session length is configured per API key and can be set up to 30 days through the Configuration section of the <Link label="Developer Portal" href="https://developer.getpara.com" /> or CLI. The Para API enforces the configured duration. Signing a message or transaction, or calling `keepSessionAlive()`, can extend an active session according to that configuration.

## Managing Sessions

### Checking Session Status

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

```typescript theme={null}
async isSessionActive(): Promise<boolean>
```

<Note>
  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.
</Note>

Example usage:

```typescript theme={null}
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.

```typescript theme={null}
async keepSessionAlive(): Promise<boolean>
```

Example usage:

```typescript theme={null}
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.

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

```typescript theme={null}
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.

```typescript theme={null}
exportSession({ excludeSigners?: boolean }): string
```

<Tip>
  If your server doesn't need to perform signing operations, use `{ excludeSigners: true }` when exporting sessions for enhanced security.
</Tip>

Example implementation:

```typescript theme={null}
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.

```typescript theme={null}
// 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();
}, []);
```

2. **Implement Automatic Session Extension**: For long app usage sessions, periodically call `keepSessionAlive()` to prevent unexpected session expirations.

```typescript theme={null}
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);
}, []);
```

3. **Handle Background/Foreground State**: React Native apps can be backgrounded and foregrounded, which may affect session status.

```typescript theme={null}
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();
  };
}, []);
```

4. **Secure Storage Configuration**: For enhanced security, consider implementing a <Link label="custom storage solution" href="/v3/react-native/guides/custom-storage" /> to manage sensitive session data.

## Next Steps

Explore more advanced features and integrations with Para in React Native:

<CardGroup cols={2}>
  <Card horizontal title="Social Login" imgUrl="/images/v3/custom-ui-social.png" href="/v3/react-native/guides/add-social-login" description="Learn how to implement social login in React Native" />

  <Card horizontal title="Custom Storage" imgUrl="/images/v3/general-storage.png" href="/v3/react-native/guides/custom-storage" description="Configure Para to use custom storage solutions" />
</CardGroup>
