Skip to content

@pubflow/core ​

The core package provides platform-agnostic functionality that works everywhere - browser, Node.js, React Native, and more. It's the foundation for all other Flowfull Client packages.

Installation ​

bash
npm install @pubflow/core

When to Use ​

Most Developers Don't Need This Package Directly

If you're building a React, React Native, or Next.js app, skip this page! Use the framework-specific packages instead:

  • React → @pubflow/react - Includes hooks, components, and SWR integration
  • React Native (Expo) → @pubflow/react-native - Mobile-optimized with SecureStore
  • Next.js → @pubflow/nextjs - SSR support, API routes, and cookie-based sessions

These packages include @pubflow/core automatically and provide a better developer experience.

Use @pubflow/core directly only when:

  • Building a custom framework adapter (Vue, Svelte, Angular, etc.)
  • Working in a non-React environment
  • Creating a Node.js backend service
  • You need low-level control over API calls and authentication

Exports ​

ApiClient ​

HTTP client with automatic authentication and error handling.

typescript
import { ApiClient } from '@pubflow/core';

const client = new ApiClient({
  baseUrl: 'https://your-backend.com',
  storage: yourStorageAdapter,
});

// Make authenticated requests
const response = await client.get('/api/users');
const user = await client.post('/api/users', { name: 'John' });

Methods ​

  • get(path, options?) - GET request
  • post(path, data, options?) - POST request
  • put(path, data, options?) - PUT request
  • patch(path, data, options?) - PATCH request
  • delete(path, options?) - DELETE request

Options ​

typescript
interface RequestOptions {
  headers?: Record<string, string>;
  params?: Record<string, any>;
  signal?: AbortSignal;
}

AuthService ​

Authentication service for login, logout, and session management.

typescript
import { AuthService } from '@pubflow/core';

const auth = new AuthService({
  baseUrl: 'https://your-backend.com',
  storage: yourStorageAdapter,
});

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

// Register
const newUser = await auth.register({
  email: 'user@example.com',
  password: 'password123',
  name: 'John Doe',
});

// Logout
await auth.logout();

// Get current user
const currentUser = await auth.getCurrentUser();

// Check if authenticated
const isAuth = await auth.isAuthenticated();

Methods ​

  • login(credentials) - Login with email/password
  • register(data) - Register new user
  • logout() - Logout and clear session
  • getCurrentUser() - Get current user data
  • isAuthenticated() - Check if user is authenticated
  • refreshSession() - Refresh current session
  • validateSession() - Validate current session

BridgeService ​

Backend-to-backend validation service for Flowfull servers.

typescript
import { BridgeService } from '@pubflow/core';

const bridge = new BridgeService({
  flowlessUrl: 'https://flowless.pubflow.com',
  instanceId: 'your-instance-id',
  instanceSecret: 'your-instance-secret',
});

// Validate session
const validation = await bridge.validateSession({
  sessionId: 'ses_...',
  ip: '192.168.1.1',
  userAgent: 'Mozilla/5.0...',
  deviceId: 'device-123',
});

if (validation.valid) {
  console.log('User:', validation.user);
  console.log('Session:', validation.session);
}

Methods ​

  • validateSession(params) - Validate a session
  • getTrustToken(sessionId) - Get trust token for session
  • validateTrustToken(token) - Validate trust token

StorageAdapter ​

Abstract storage interface that must be implemented for each platform.

typescript
import { StorageAdapter } from '@pubflow/core';

class CustomStorageAdapter implements StorageAdapter {
  async getItem(key: string): Promise<string | null> {
    // Your implementation
  }

  async setItem(key: string, value: string): Promise<void> {
    // Your implementation
  }

  async removeItem(key: string): Promise<void> {
    // Your implementation
  }

  async clear(): Promise<void> {
    // Your implementation
  }
}

Built-in Adapters ​

  • LocalStorageAdapter (@pubflow/react) - Browser localStorage
  • SecureStorageAdapter (@pubflow/react-native) - AsyncStorage + SecureStore
  • ServerStorageAdapter (@pubflow/nextjs) - Cookie-based storage
  • ClientStorageAdapter (@pubflow/nextjs) - Browser localStorage

Types ​

User ​

typescript
interface User {
  id: string;
  email: string;
  name: string;
  picture?: string;
  email_verified: boolean;
  created_at: string;
  updated_at: string;
  [key: string]: any; // Custom fields
}

Session ​

typescript
interface Session {
  id: string;
  user_id: string;
  expires_at: string;
  created_at: string;
  ip?: string;
  user_agent?: string;
  device_id?: string;
}

PubflowInstanceConfig ​

typescript
interface PubflowInstanceConfig {
  url: string;
  instanceId?: string;
  storage?: StorageAdapter;
  onAuthError?: (error: Error) => void;
  onSessionExpired?: () => void;
}

LoginCredentials ​

typescript
interface LoginCredentials {
  email: string;
  password: string;
}

RegisterData ​

typescript
interface RegisterData {
  email: string;
  password: string;
  name: string;
  [key: string]: any; // Additional fields
}

Example: Custom Integration ​

Here's a complete example of using @pubflow/core in a custom environment:

typescript
import { ApiClient, AuthService, StorageAdapter } from '@pubflow/core';

// 1. Implement storage adapter
class MemoryStorageAdapter implements StorageAdapter {
  private storage = new Map<string, string>();

  async getItem(key: string): Promise<string | null> {
    return this.storage.get(key) || null;
  }

  async setItem(key: string, value: string): Promise<void> {
    this.storage.set(key, value);
  }

  async removeItem(key: string): Promise<void> {
    this.storage.delete(key);
  }

  async clear(): Promise<void> {
    this.storage.clear();
  }
}

// 2. Create instances
const storage = new MemoryStorageAdapter();
const apiClient = new ApiClient({
  baseUrl: 'https://your-backend.com',
  storage,
});
const authService = new AuthService({
  baseUrl: 'https://your-backend.com',
  storage,
});

// 3. Use the services
async function main() {
  // Login
  const user = await authService.login({
    email: 'user@example.com',
    password: 'password123',
  });
  console.log('Logged in:', user);

  // Make API call
  const data = await apiClient.get('/api/users');
  console.log('Users:', data);

  // Logout
  await authService.logout();
  console.log('Logged out');
}

main();

Example: Node.js Backend ​

Using @pubflow/core in a Node.js backend to validate sessions:

typescript
import { BridgeService } from '@pubflow/core';
import express from 'express';

const app = express();
const bridge = new BridgeService({
  flowlessUrl: process.env.FLOWLESS_URL!,
  instanceId: process.env.INSTANCE_ID!,
  instanceSecret: process.env.INSTANCE_SECRET!,
});

// Middleware to validate sessions
app.use(async (req, res, next) => {
  const sessionId = req.headers['x-session-id'] as string;

  if (!sessionId) {
    return res.status(401).json({ error: 'No session provided' });
  }

  try {
    const validation = await bridge.validateSession({
      sessionId,
      ip: req.ip,
      userAgent: req.headers['user-agent'],
    });

    if (!validation.valid) {
      return res.status(401).json({ error: 'Invalid session' });
    }

    // Attach user to request
    req.user = validation.user;
    next();
  } catch (error) {
    res.status(500).json({ error: 'Session validation failed' });
  }
});

app.get('/api/profile', (req, res) => {
  res.json({ user: req.user });
});

app.listen(3000);

API Reference ​

For complete API documentation, see:

Next Steps ​