Skip to content

Authentication ​

This guide covers how to handle user authentication with Flowfull Client.

How Authentication Works ​

Flowfull Client automatically handles session management:

  1. Login - Send credentials to your backend
  2. Store Session - Session ID is automatically stored
  3. Auto-Include - All future requests include the session automatically
  4. Logout - Clear the session when logging out

Basic Authentication ​

Login ​

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

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

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

// Session is automatically stored!
console.log('Logged in:', response.user);

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

Logout ​

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

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

React Example ​

Here's a complete authentication example in React:

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

function LoginForm() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  async function handleLogin(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    setError('');

    try {
      const response = await api.post('/auth/login', {
        email: email.toLowerCase(),
        password
      });
      
      console.log('Logged in:', response.user);
      // Redirect to dashboard or home page
      window.location.href = '/dashboard';
    } catch (err: any) {
      setError(err.message || 'Login failed');
    } finally {
      setLoading(false);
    }
  }

  return (
    <form onSubmit={handleLogin}>
      <input
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        placeholder="Email"
        required
      />
      <input
        type="password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
        placeholder="Password"
        required
      />
      <button type="submit" disabled={loading}>
        {loading ? 'Logging in...' : 'Login'}
      </button>
      {error && <div style={{ color: 'red' }}>{error}</div>}
    </form>
  );
}

React Native Example ​

typescript
import { useState } from 'react';
import { View, TextInput, Button, Text, Alert } from 'react-native';
import { api } from '../lib/api';

export default function LoginScreen({ navigation }) {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);

  async function handleLogin() {
    setLoading(true);

    try {
      const response = await api.post('/auth/login', {
        email: email.toLowerCase(),
        password
      });
      
      console.log('Logged in:', response.user);
      navigation.navigate('Home');
    } catch (error: any) {
      Alert.alert('Login Failed', error.message || 'Please try again');
    } finally {
      setLoading(false);
    }
  }

  return (
    <View style={{ padding: 20 }}>
      <TextInput
        value={email}
        onChangeText={setEmail}
        placeholder="Email"
        keyboardType="email-address"
        autoCapitalize="none"
        style={{ borderWidth: 1, padding: 10, marginBottom: 10 }}
      />
      <TextInput
        value={password}
        onChangeText={setPassword}
        placeholder="Password"
        secureTextEntry
        style={{ borderWidth: 1, padding: 10, marginBottom: 10 }}
      />
      <Button
        title={loading ? 'Logging in...' : 'Login'}
        onPress={handleLogin}
        disabled={loading}
      />
    </View>
  );
}

Custom Authentication Hook (React) ​

Create a reusable authentication hook:

typescript
// src/hooks/useAuth.ts
import { useState, useEffect } from 'react';
import { api } from '../lib/api';

export function useAuth() {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    checkAuth();
  }, []);

  async function checkAuth() {
    try {
      const userData = await api.get('/auth/me');
      setUser(userData);
    } catch (error) {
      setUser(null);
    } finally {
      setLoading(false);
    }
  }

  async function login(email: string, password: string) {
    const response = await api.post('/auth/login', {
      email: email.toLowerCase(),
      password
    });
    setUser(response.user);
    return response;
  }

  async function logout() {
    await api.post('/auth/logout');
    api.clearSession();
    setUser(null);
  }

  return {
    user,
    loading,
    isAuthenticated: !!user,
    login,
    logout,
    refetch: checkAuth
  };
}

Session Management ​

Check if User is Logged In ​

typescript
const sessionId = api.getSessionId();

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

Clear Session ​

typescript
api.clearSession();

Next Steps ​