Skip to content

Session Management ​

This guide covers how Flowfull Client handles user sessions.

How Sessions Work ​

Flowfull Client automatically manages sessions for you:

  1. Login - When you login, the session ID is automatically stored
  2. Auto-Include - All future requests automatically include the session
  3. Platform-Specific Storage - Uses the right storage for your platform
  4. Logout - Clear the session when logging out

Automatic Session Storage ​

Sessions are automatically stored based on your platform:

PlatformStorage UsedKey Name
BrowserlocalStorageflowfull_session_id
React NativeAsyncStorageflowfull_session_id
Next.js ServerManual (cookies)Custom

Login and Session Storage ​

typescript
import { createFlowfull } from '@pubflow/flowfull-client';

const api = createFlowfull('https://api.example.com');

// Login - session is automatically stored
const response = await api.post('/auth/login', {
  email: 'user@example.com',
  password: 'password123'
});

console.log('Session ID:', response.session_id);
// Session is now stored in localStorage/AsyncStorage

// All future requests include the session automatically
const profile = await api.get('/profile');

Check if User is Logged In ​

typescript
// Get the current session ID
const sessionId = api.getSessionId();

if (sessionId) {
  console.log('User is logged in');
  console.log('Session ID:', sessionId);
} else {
  console.log('User is not logged in');
}

Logout and Clear Session ​

typescript
// Logout from backend
await api.post('/auth/logout');

// Clear session from storage
api.clearSession();

console.log('User logged out');

Manual Session Management ​

For advanced use cases, you can manually manage sessions:

Set Session ID ​

typescript
// Set a session ID manually
api.setSessionId('your-session-id-here');

// All future requests will use this session
const profile = await api.get('/profile');

Get Session ID ​

typescript
const sessionId = api.getSessionId();
console.log('Current session:', sessionId);

Clear Session ​

typescript
api.clearSession();
console.log('Session cleared');

Next.js Server Components ​

For Next.js server components, use manual session management with cookies:

typescript
// lib/api-server.ts
import { createFlowfull } from '@pubflow/flowfull-client';
import { cookies } from 'next/headers';

export async function getServerApi() {
  const sessionId = cookies().get('session_id')?.value;
  
  return createFlowfull(process.env.NEXT_PUBLIC_API_URL!, {
    sessionId
  });
}

Usage in server component:

typescript
// app/profile/page.tsx
import { getServerApi } from '@/lib/api-server';

export default async function ProfilePage() {
  const api = await getServerApi();
  const profile = await api.get('/profile');

  return (
    <div>
      <h1>{profile.name}</h1>
      <p>{profile.email}</p>
    </div>
  );
}

Session Persistence ​

Sessions are automatically persisted across app restarts:

typescript
// First visit - login
await api.post('/auth/login', { email, password });

// Close and reopen app

// Session is still available
const profile = await api.get('/profile'); // Works!

Custom Storage ​

You can provide a custom storage adapter:

typescript
import { createFlowfull } from '@pubflow/flowfull-client';

const customStorage = {
  async getItem(key: string): Promise<string | null> {
    // Your custom get logic
    return localStorage.getItem(key);
  },
  async setItem(key: string, value: string): Promise<void> {
    // Your custom set logic
    localStorage.setItem(key, value);
  },
  async removeItem(key: string): Promise<void> {
    // Your custom remove logic
    localStorage.removeItem(key);
  }
};

const api = createFlowfull('https://api.example.com', {
  storage: customStorage
});

Session Validation ​

Check if the current session is still valid:

typescript
try {
  const user = await api.get('/auth/me');
  console.log('Session is valid:', user);
} catch (error: any) {
  if (error.status === 401) {
    console.log('Session expired or invalid');
    api.clearSession();
    // Redirect to login
  }
}

React Hook Example ​

Create a custom hook for session management:

typescript
import { useState, useEffect } from 'react';
import { api } from '../lib/api';

export function useSession() {
  const [sessionId, setSessionId] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const id = api.getSessionId();
    setSessionId(id);
    setLoading(false);
  }, []);

  function clearSession() {
    api.clearSession();
    setSessionId(null);
  }

  return {
    sessionId,
    isLoggedIn: !!sessionId,
    loading,
    clearSession
  };
}

Next Steps ​