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.

📚 Documentation ​

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
  • Building payment processing integrations

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

BridgePaymentClient ​

Complete payment processing client for Bridge Payments with support for Stripe, PayPal, Authorize.net, and more.

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

const payments = new BridgePaymentClient({
  baseUrl: 'https://your-bridge-payments.com',
  // Optional: Automatic session-based authentication
  getSessionId: async () => {
    return localStorage.getItem('pubflow_session_id');
  },
  // Optional: Guest token authentication
  guestToken: 'guest_token_...',
  // Optional: Organization ID for multi-tenant
  organizationId: 'org_...',
});

// Create payment intent
const intent = await payments.createPaymentIntent({
  total_cents: 2000, // $20.00
  currency: 'USD',
  description: 'Premium Plan Subscription',
  provider_id: 'stripe',
});

// Create payment method
const paymentMethod = await payments.createPaymentMethod({
  type: 'card',
  card_token: 'tok_visa', // From Stripe.js
  is_default: true,
});

// Create subscription
const subscription = await payments.createSubscription({
  plan_id: 'plan_premium',
  payment_method_id: paymentMethod.id,
});

// List customer's payment methods
const methods = await payments.listPaymentMethods();

// Get payment history
const payments = await payments.listPayments({ limit: 10 });

Configuration ​

typescript
interface BridgePaymentConfig {
  baseUrl: string;                          // Bridge Payments server URL
  getSessionId?: () => Promise<string | null>; // Session-based auth
  guestToken?: string;                      // Guest token auth
  organizationId?: string;                  // Multi-tenant organization ID
  headers?: Record<string, string>;         // Custom headers
}

Payment Methods ​

Payment Intents:

  • createPaymentIntent(data) - Create new payment intent
  • getPaymentIntent(id) - Get payment intent details
  • listPaymentIntents(params?) - List payment intents

Payment Methods:

  • createPaymentMethod(data) - Add payment method (card, bank account)
  • getPaymentMethod(id) - Get payment method details
  • updatePaymentMethod(id, data) - Update payment method
  • deletePaymentMethod(id) - Remove payment method
  • listPaymentMethods(params?) - List customer's payment methods

Payments:

  • getPayment(id) - Get payment details
  • listPayments(params?) - List payment history

Addresses:

  • createAddress(data) - Add billing/shipping address
  • getAddress(id) - Get address details
  • updateAddress(id, data) - Update address
  • deleteAddress(id) - Remove address
  • listAddresses(params?) - List customer's addresses

Customers:

  • createCustomer(data) - Create customer profile
  • getCustomer(id) - Get customer details
  • updateCustomer(id, data) - Update customer
  • deleteCustomer(id) - Delete customer
  • listCustomers(params?) - List customers (admin)

Subscriptions:

  • createSubscription(data) - Create subscription
  • getSubscription(id) - Get subscription details
  • cancelSubscription(id, data?) - Cancel subscription
  • listSubscriptions(params?) - List subscriptions

Organizations (Multi-tenant):

  • createOrganization(data) - Create organization
  • getOrganization(id) - Get organization details
  • updateOrganization(id, data) - Update organization
  • deleteOrganization(id) - Delete organization
  • listOrganizations(params?) - List organizations
  • addOrganizationMember(orgId, data) - Add member
  • removeOrganizationMember(orgId, userId) - Remove member
  • updateOrganizationMemberRole(orgId, userId, data) - Update member role
  • listOrganizationMembers(orgId, params?) - List members

Guest Conversion:

  • convertGuestToUser(data) - Convert guest checkout to registered user

Example: Complete Checkout Flow ​

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

// Initialize client with session-based auth
const payments = new BridgePaymentClient({
  baseUrl: process.env.BRIDGE_PAYMENTS_URL!,
  getSessionId: async () => localStorage.getItem('pubflow_session_id'),
});

async function checkout() {
  // 1. Create payment intent
  const intent = await payments.createPaymentIntent({
    total_cents: 5000, // $50.00
    currency: 'USD',
    description: 'Product Purchase',
    provider_id: 'stripe',
  });

  // 2. Collect payment details (using Stripe.js, PayPal SDK, etc.)
  const cardToken = await stripe.createToken(cardElement);

  // 3. Create payment method
  const paymentMethod = await payments.createPaymentMethod({
    type: 'card',
    card_token: cardToken.id,
    is_default: true,
  });

  // 4. Process payment (handled by Bridge Payments backend)
  console.log('Payment successful!', intent);
}

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 ​