---
url: /examples/saas-dashboard.md
---
# 📊 SaaS Dashboard
Build a complete SaaS platform with team management, API keys, analytics, and billing.
::: info 📖 Cross-Ecosystem Example
This is a **complete tutorial** demonstrating the standard Flowfull architecture pattern using **flowfull-node** for your custom SaaS backend.
:::
## 🎯 What You'll Build
A production-ready SaaS dashboard with:
* ✅ Team management with role-based access
* ✅ API key generation and management
* ✅ Usage analytics and metrics
* ✅ Webhook management
* ✅ Team billing and subscriptions
* ✅ Activity logs and audit trail
* ✅ Admin panel
**Time to complete:** ~150 minutes
***
## 🛠️ Tech Stack
| Component | Technology | Purpose |
|-----------|-----------|---------|
| 🔐 **Flowless** | Managed Service (pubflow.com) | Authentication - Team auth, OAuth, roles |
| ⚡ **Flowfull** | Node.js (flowfull-node) | **Your custom backend** - Analytics, webhooks, API keys, teams |
| 🎨 **Flowfull Clients** | React (@pubflow/react) | **Your frontend** - Dashboard with charts and analytics |
| 💳 **Bridge Payments** | Managed Service | Payment processing - Team subscriptions, usage billing |
::: tip 🏗️ Standard Architecture Pattern
* **Flowless** = Authentication backend (managed, no code needed)
* **Flowfull** = Your custom backend using flowfull-node (you write this)
* **Flowfull Clients** = Your frontend using @pubflow/react (you write this)
* **Bridge Payments** = Payment backend (managed, API integration only)
:::
***
## 🏗️ Architecture
```mermaid
graph TB
subgraph "🎨 Your Frontend (React)"
A["Team Dashboard (@pubflow/react)"]
B["API Keys Manager (React Components)"]
C["Analytics (Charts & Metrics)"]
D["Billing Portal (Bridge Payments UI)"]
end
subgraph "⚡ Your Backend (Flowfull)"
E["Analytics API (flowfull-node)"]
F["Webhooks API (Node.js + Database)"]
G["API Keys API (Custom Business Logic)"]
H["Teams API (Multi-tenant Logic)"]
end
subgraph "☁️ Pubflow Managed Services"
I["🔐 Flowless (pubflow.com)"]
J["💳 Bridge Payments (Subscription Billing)"]
end
A -->|"Manage Teams"| H
B -->|"Generate Keys"| G
C -->|"Track Usage"| E
D -->|"Subscribe"| J
E -->|"Validate Sessions"| I
F -->|"Bridge Validation"| I
G -->|"Auth Check"| I
H -->|"Auth Check"| I
J -->|"Billing Webhooks"| E
style A fill:#4CAF50,stroke:#2E7D32,stroke-width:3px,color:#fff
style E fill:#2196F3,stroke:#1565C0,stroke-width:3px,color:#fff
style I fill:#FF9800,stroke:#E65100,stroke-width:3px,color:#fff
style J fill:#9C27B0,stroke:#6A1B9A,stroke-width:3px,color:#fff
```
**Flow:**
1. Frontend (React) → Your Backend (Flowfull/flowfull-node)
2. Your Backend → Flowless for authentication
3. Your Backend → Bridge Payments for subscription billing
4. Bridge Payments → Your Backend (webhooks for billing events)
***
## 📋 Prerequisites
* ✅ **Bun** v1.0+ ([Install](https://bun.sh)) or Node.js 18+
* ✅ **Database** - PostgreSQL, MySQL, or LibSQL/Turso
* ✅ **Pubflow account** - Sign up at [pubflow.com](https://pubflow.com)
* ✅ **Code Editor** - VS Code, Cursor, or your favorite editor
* ✅ Basic knowledge of React and TypeScript
***
## 🚀 Step 1: Setup Flowless Authentication (5 min)
### 1.1 Create Flowless Instance
1. Visit [pubflow.com](https://pubflow.com)
2. Sign up or log in
3. Click **"Create Flowless Instance"**
4. Name it: `saas-auth`
5. Copy your **Bridge Secret**
Your Flowless URL will be:
```
https://saas-auth.pubflow.com
```
::: tip 📖 Learn More
For detailed Flowless setup, see [Flowless Getting Started](https://flowless.dev/getting-started)
:::
***
## ⚡ Step 2: Setup Flowfull Backend (10 min)
### 2.1 Clone flowfull-node (Official Starter Kit)
::: tip 📦 Official Starter Kit
**flowfull-node** is the official, production-ready starter kit maintained by the Pubflow team.
[View Documentation →](https://flowfull.dev/getting-started)
:::
```bash
# Clone the official flowfull-node template
git clone https://github.com/pubflow/flowfull-node.git saas-backend
cd saas-backend
# Install dependencies
bun install
# or: npm install
```
### 2.2 Configure Environment Variables
Copy the example environment file:
```bash
cp .env.example .env
```
Edit `.env` with your configuration:
```env
# Flowless Configuration
FLOWLESS_API_URL=https://saas-auth.pubflow.com
BRIDGE_VALIDATION_SECRET=your_bridge_secret_here
# Database
DATABASE_URL=postgresql://user:pass@localhost:5432/saas
# Server
PORT=3001
NODE_ENV=development
# Optional: Cache
REDIS_URL=redis://localhost:6379
```
::: info 🔧 Environment Variables
* `FLOWLESS_API_URL`: Your Flowless instance URL from Step 1
* `BRIDGE_VALIDATION_SECRET`: Bridge secret from Pubflow dashboard
* `DATABASE_URL`: Your PostgreSQL/MySQL/LibSQL connection string
:::
***
## 📊 Step 3: Database Schema
```sql
-- Teams
CREATE TABLE teams (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name VARCHAR(255) NOT NULL,
owner_id VARCHAR(255) NOT NULL,
plan VARCHAR(50) DEFAULT 'free',
created_at TIMESTAMP DEFAULT NOW()
);
-- Team Members
CREATE TABLE team_members (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
team_id UUID REFERENCES teams(id) ON DELETE CASCADE,
user_id VARCHAR(255) NOT NULL,
role VARCHAR(50) DEFAULT 'member',
created_at TIMESTAMP DEFAULT NOW(),
UNIQUE(team_id, user_id)
);
-- API Keys
CREATE TABLE api_keys (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
team_id UUID REFERENCES teams(id) ON DELETE CASCADE,
name VARCHAR(255) NOT NULL,
key_hash VARCHAR(255) NOT NULL,
prefix VARCHAR(20) NOT NULL,
last_used_at TIMESTAMP,
created_at TIMESTAMP DEFAULT NOW()
);
-- Webhooks
CREATE TABLE webhooks (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
team_id UUID REFERENCES teams(id) ON DELETE CASCADE,
url VARCHAR(1000) NOT NULL,
events JSONB DEFAULT '[]',
secret VARCHAR(255) NOT NULL,
active BOOLEAN DEFAULT true,
created_at TIMESTAMP DEFAULT NOW()
);
-- Analytics Events
CREATE TABLE analytics_events (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
team_id UUID REFERENCES teams(id) ON DELETE CASCADE,
event_type VARCHAR(100) NOT NULL,
metadata JSONB,
created_at TIMESTAMP DEFAULT NOW()
);
-- Usage Metrics
CREATE TABLE usage_metrics (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
team_id UUID REFERENCES teams(id) ON DELETE CASCADE,
metric_type VARCHAR(100) NOT NULL,
value INTEGER NOT NULL,
period DATE NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
```
***
## ⚡ Step 1: Team Management API
```typescript
// src/routes/teams.ts
import { Hono } from 'hono'
import { validateSession } from '../middleware/auth'
const teams = new Hono()
// Create team
teams.post('/', validateSession, async (c) => {
const user = c.get('user')
const { name } = await c.req.json()
const team = await db
.insertInto('teams')
.values({
name,
owner_id: user.id,
plan: 'free'
})
.returningAll()
.executeTakeFirst()
// Add owner as admin
await db
.insertInto('team_members')
.values({
team_id: team.id,
user_id: user.id,
role: 'admin'
})
.execute()
return c.json({ team }, 201)
})
// Get team members
teams.get('/:teamId/members', validateSession, async (c) => {
const teamId = c.req.param('teamId')
const members = await db
.selectFrom('team_members')
.selectAll()
.where('team_id', '=', teamId)
.execute()
return c.json({ members })
})
// Invite member
teams.post('/:teamId/invite', validateSession, async (c) => {
const teamId = c.req.param('teamId')
const { email, role } = await c.req.json()
// Send invitation email
// Add to team_members when accepted
return c.json({ success: true })
})
```
***
## 🔑 Step 2: API Keys Management
```typescript
// src/routes/api-keys.ts
import { Hono } from 'hono'
import { createHash, randomBytes } from 'crypto'
const apiKeys = new Hono()
// Generate API key
apiKeys.post('/', validateSession, async (c) => {
const user = c.get('user')
const { team_id, name } = await c.req.json()
// Generate key
const key = `sk_${randomBytes(32).toString('hex')}`
const keyHash = createHash('sha256').update(key).digest('hex')
const prefix = key.substring(0, 12)
const apiKey = await db
.insertInto('api_keys')
.values({
team_id,
name,
key_hash: keyHash,
prefix
})
.returningAll()
.executeTakeFirst()
// Return full key only once
return c.json({ api_key: { ...apiKey, key } }, 201)
})
// List API keys
apiKeys.get('/team/:teamId', validateSession, async (c) => {
const teamId = c.req.param('teamId')
const keys = await db
.selectFrom('api_keys')
.select(['id', 'name', 'prefix', 'last_used_at', 'created_at'])
.where('team_id', '=', teamId)
.execute()
return c.json({ keys })
})
```
***
## 📊 Step 3: Analytics Dashboard
```tsx
// src/pages/analytics.tsx
import { useBridge } from '@pubflow/react'
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip } from 'recharts'
export default function AnalyticsPage() {
const { data: metrics } = useBridge('/analytics/metrics?period=7d')
return (
Analytics
API Calls
{metrics?.api_calls || 0}
+12% from last week
Active Users
{metrics?.active_users || 0}
+8% from last week
Success Rate
{metrics?.success_rate || 0}%
Last 7 days
API Usage
)
}
```
***
## 💳 Step 4: Team Billing
```tsx
// src/pages/billing.tsx
import { useState } from 'react'
import { useAuth } from '@pubflow/react'
export default function BillingPage() {
const { user } = useAuth()
const [loading, setLoading] = useState(false)
const plans = [
{ name: 'Free', price: 0, calls: 1000 },
{ name: 'Pro', price: 29, calls: 100000 },
{ name: 'Enterprise', price: 299, calls: 'Unlimited' }
]
const handleUpgrade = async (plan: string) => {
setLoading(true)
const response = await fetch('/api/billing/subscribe', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Session-Id': localStorage.getItem('pubflow_session_id') || ''
},
body: JSON.stringify({ plan })
})
const { client_secret } = await response.json()
window.location.href = `https://checkout.stripe.com/${client_secret}`
}
return (
Billing
{plans.map((plan) => (
{plan.name}
${plan.price}/mo
{plan.calls} API calls/month
handleUpgrade(plan.name.toLowerCase())}
disabled={loading}
className="w-full bg-blue-600 text-white py-2 rounded"
>
{loading ? 'Processing...' : 'Upgrade'}
))}
)
}
```
***
## 🎉 Result
You've built a complete SaaS dashboard with:
* ✅ Team management
* ✅ API key generation
* ✅ Analytics dashboard
* ✅ Billing integration
***
## 📖 Next Steps
* 🔔 **Notifications** - Real-time alerts
* 📧 **Email reports** - Weekly summaries
* 🔒 **2FA** - Enhanced security
* 📱 **Mobile app** - iOS/Android dashboard
***
## 📚 Related Resources
* 🔐 **[Flowless Documentation](/)** - Authentication
* ⚡ **[Flowfull Documentation](https://flowfull.dev)** - Backend
* 💳 **[Bridge Payments](https://bridgepayments.dev)** - Billing
* 💬 **[Discord](https://discord.gg/EJfPTT6Vh7)** - Community
---
---
url: /examples/full-stack-blog.md
---
# 📝 Full-Stack Blog App
Build a complete blog application with authentication, posts, comments, and premium subscriptions.
::: info 📖 Cross-Ecosystem Example
This is a **complete tutorial** showing how to build a full-stack application using the Pubflow ecosystem. It demonstrates the standard Flowfull architecture pattern using **flowfull-node** for the backend.
:::
## 🎯 What You'll Build
A production-ready blog platform with:
* ✅ User authentication (register, login, logout)
* ✅ Create, edit, and delete blog posts
* ✅ Comments system with nested replies
* ✅ Premium subscriptions ($9.99/month)
* ✅ Admin dashboard for content moderation
* ✅ Rich text editor with image uploads
* ✅ SEO-optimized with meta tags
* ✅ Responsive design (mobile + desktop)
**Time to complete:** ~90 minutes
***
## 🛠️ Tech Stack
This example demonstrates the complete Pubflow ecosystem:
| Component | Technology | Purpose |
|-----------|-----------|---------|
| 🔐 **Flowless** | Managed Service (pubflow.com) | Authentication backend - handles user registration, login, sessions, OAuth |
| ⚡ **Flowfull** | Node.js (flowfull-node) | **Your custom backend** with business logic - Posts CRUD, comments, user profiles |
| 🎨 **Flowfull Clients** | React (@pubflow/react) | **Your frontend** - React components, hooks, routing |
| 💳 **Bridge Payments** | Managed Service (optional) | Payment processing - Monthly billing, payment methods |
::: tip 🏗️ Standard Architecture Pattern
* **Flowless** = Authentication backend (managed, no code needed)
* **Flowfull** = Your custom backend using flowfull-node (you write this)
* **Flowfull Clients** = Your frontend using @pubflow/react (you write this)
:::
***
## 🏗️ Architecture
```mermaid
graph TB
subgraph "🎨 Your Frontend (React)"
A["Blog UI (Flowfull Clients)"]
B["Post Editor (@pubflow/react)"]
C["Comments Section (React Components)"]
D["Subscription Portal (Bridge Payments UI)"]
end
subgraph "⚡ Your Backend (Flowfull)"
E["Posts API (flowfull-node)"]
F["Comments API (Node.js + Express/Hono)"]
G["User Profiles API (Custom Business Logic)"]
end
subgraph "☁️ Pubflow Managed Services"
H["🔐 Flowless (pubflow.com)"]
I["💳 Bridge Payments (Optional)"]
end
A -->|"API Requests"| E
B -->|"Create/Edit Posts"| E
C -->|"Post Comments"| F
D -->|"Subscribe"| I
E -->|"Validate Sessions"| H
F -->|"Bridge Validation"| H
G -->|"Auth Check"| H
style A fill:#4CAF50,stroke:#2E7D32,stroke-width:3px,color:#fff
style E fill:#2196F3,stroke:#1565C0,stroke-width:3px,color:#fff
style H fill:#FF9800,stroke:#E65100,stroke-width:3px,color:#fff
style I fill:#9C27B0,stroke:#6A1B9A,stroke-width:3px,color:#fff
```
**Flow:**
1. Frontend (React) → Your Backend (Flowfull/flowfull-node)
2. Your Backend → Flowless (pubflow.com) for session validation
3. Flowless → Your Backend (Trust Token with user data)
4. Your Backend → Frontend (Protected data)
***
## 📋 Prerequisites
Before starting, make sure you have:
* ✅ **Bun** v1.0+ ([Install](https://bun.sh)) or Node.js 18+
* ✅ **Database** - PostgreSQL, MySQL, or LibSQL/Turso
* ✅ **Pubflow account** - Sign up at [pubflow.com](https://pubflow.com)
* ✅ **Code Editor** - VS Code, Cursor, or your favorite editor
* ✅ Basic knowledge of React and TypeScript
***
## 🚀 Step 1: Setup Flowless Authentication (5 min)
### 1.1 Create Flowless Instance
1. Visit [pubflow.com](https://pubflow.com)
2. Sign up or log in
3. Click **"Create Flowless Instance"**
4. Name it: `blog-auth`
5. Copy your **Bridge Secret** (you'll need this later)
Your Flowless URL will be:
```
https://blog-auth.pubflow.com
```
### 1.2 Configure Email Templates (Optional)
Enable email verification and password reset:
1. Go to Instance Settings → Email
2. Enable "Email Verification"
3. Enable "Password Reset"
4. Customize email templates (optional)
::: tip 📖 Learn More
For detailed Flowless setup, see [Flowless Getting Started](https://flowless.dev/getting-started)
:::
### 1.3 Test Authentication
Use the [API Playground](/playground) to test:
```bash
# Register a test user
curl -X POST https://your-instance.pubflow.com/auth/register \
-H "Content-Type: application/json" \
-d '{
"email": "test@example.com",
"password": "SecurePass123!",
"name": "Test User"
}'
```
✅ **Checkpoint:** You should receive a session\_id in the response.
***
## ⚡ Step 2: Build Flowfull Backend (30 min)
### 2.1 Clone flowfull-node (Official Starter Kit)
::: tip 📦 Official Starter Kit
**flowfull-node** is the official, production-ready starter kit maintained by the Pubflow team. It includes all core features, best practices, and is regularly updated.
[View Documentation →](https://flowfull.dev/getting-started)
:::
```bash
# Clone the official flowfull-node template
git clone https://github.com/pubflow/flowfull-node.git blog-backend
cd blog-backend
# Install dependencies
bun install
# or: npm install
```
### 2.2 Configure Environment Variables
Copy the example environment file:
```bash
cp .env.example .env
```
Edit `.env` with your configuration:
```env
# Flowless Configuration
FLOWLESS_API_URL=https://blog-auth.pubflow.com
BRIDGE_VALIDATION_SECRET=your_bridge_secret_here
# Database
DATABASE_URL=postgresql://user:pass@localhost:5432/blog
# Server
PORT=3001
NODE_ENV=development
# Optional: Cache (for better performance)
REDIS_URL=redis://localhost:6379
```
::: info 🔧 Environment Variables
* `FLOWLESS_API_URL`: Your Flowless instance URL from Step 1
* `BRIDGE_VALIDATION_SECRET`: Bridge secret from Pubflow dashboard
* `DATABASE_URL`: Your PostgreSQL/MySQL/LibSQL connection string
:::
### 2.3 Create Database Schema
Create `schema.sql`:
```sql
-- Posts table
CREATE TABLE posts (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id VARCHAR(255) NOT NULL,
title VARCHAR(500) NOT NULL,
slug VARCHAR(500) UNIQUE NOT NULL,
content TEXT NOT NULL,
excerpt TEXT,
cover_image VARCHAR(1000),
published BOOLEAN DEFAULT false,
premium_only BOOLEAN DEFAULT false,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
-- Comments table
CREATE TABLE comments (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
post_id UUID REFERENCES posts(id) ON DELETE CASCADE,
user_id VARCHAR(255) NOT NULL,
parent_id UUID REFERENCES comments(id) ON DELETE CASCADE,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
-- Indexes for performance
CREATE INDEX IF NOT EXIST idx_posts_user_id ON posts(user_id);
CREATE INDEX IF NOT EXIST idx_posts_slug ON posts(slug);
CREATE INDEX IF NOT EXIST idx_comments_post_id ON comments(post_id);
CREATE INDEX IF NOT EXIST idx_comments_parent_id ON comments(parent_id);
```
Run migrations:
```bash
psql $DATABASE_URL < schema.sql
```
### 2.4 Implement Posts API
Create `src/routes/posts.ts`:
```typescript
import { Hono } from 'hono'
import { validateSession } from '../middleware/auth'
import { db } from '../db'
const posts = new Hono()
// Get all posts (public)
posts.get('/', async (c) => {
const posts = await db
.selectFrom('posts')
.selectAll()
.where('published', '=', true)
.orderBy('created_at', 'desc')
.execute()
return c.json({ posts })
})
// Get single post by slug
posts.get('/:slug', async (c) => {
const slug = c.req.param('slug')
const post = await db
.selectFrom('posts')
.selectAll()
.where('slug', '=', slug)
.where('published', '=', true)
.executeTakeFirst()
if (!post) {
return c.json({ error: 'Post not found' }, 404)
}
return c.json({ post })
})
// Create post (authenticated)
posts.post('/', validateSession, async (c) => {
const user = c.get('user')
const { title, content, excerpt, cover_image, premium_only } = await c.req.json()
// Generate slug from title
const slug = title.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/(^-|-$)/g, '')
const post = await db
.insertInto('posts')
.values({
user_id: user.id,
title,
slug,
content,
excerpt,
cover_image,
premium_only: premium_only || false,
published: false
})
.returningAll()
.executeTakeFirst()
return c.json({ post }, 201)
})
// Update post (authenticated, owner only)
posts.put('/:id', validateSession, async (c) => {
const user = c.get('user')
const id = c.req.param('id')
const { title, content, excerpt, cover_image, published, premium_only } = await c.req.json()
// Check ownership
const existing = await db
.selectFrom('posts')
.select('user_id')
.where('id', '=', id)
.executeTakeFirst()
if (!existing || existing.user_id !== user.id) {
return c.json({ error: 'Unauthorized' }, 403)
}
const post = await db
.updateTable('posts')
.set({
title,
content,
excerpt,
cover_image,
published,
premium_only,
updated_at: new Date()
})
.where('id', '=', id)
.returningAll()
.executeTakeFirst()
return c.json({ post })
})
// Delete post (authenticated, owner only)
posts.delete('/:id', validateSession, async (c) => {
const user = c.get('user')
const id = c.req.param('id')
const existing = await db
.selectFrom('posts')
.select('user_id')
.where('id', '=', id)
.executeTakeFirst()
if (!existing || existing.user_id !== user.id) {
return c.json({ error: 'Unauthorized' }, 403)
}
await db
.deleteFrom('posts')
.where('id', '=', id)
.execute()
return c.json({ success: true })
})
export default posts
```
### 2.5 Implement Comments API
Create `src/routes/comments.ts`:
```typescript
import { Hono } from 'hono'
import { validateSession } from '../middleware/auth'
import { db } from '../db'
const comments = new Hono()
// Get comments for a post
comments.get('/post/:postId', async (c) => {
const postId = c.req.param('postId')
const comments = await db
.selectFrom('comments')
.selectAll()
.where('post_id', '=', postId)
.orderBy('created_at', 'asc')
.execute()
return c.json({ comments })
})
// Create comment (authenticated)
comments.post('/', validateSession, async (c) => {
const user = c.get('user')
const { post_id, parent_id, content } = await c.req.json()
const comment = await db
.insertInto('comments')
.values({
post_id,
parent_id: parent_id || null,
user_id: user.id,
content
})
.returningAll()
.executeTakeFirst()
return c.json({ comment }, 201)
})
// Delete comment (authenticated, owner only)
comments.delete('/:id', validateSession, async (c) => {
const user = c.get('user')
const id = c.req.param('id')
const existing = await db
.selectFrom('comments')
.select('user_id')
.where('id', '=', id)
.executeTakeFirst()
if (!existing || existing.user_id !== user.id) {
return c.json({ error: 'Unauthorized' }, 403)
}
await db
.deleteFrom('comments')
.where('id', '=', id)
.execute()
return c.json({ success: true })
})
export default comments
```
✅ **Checkpoint:** Test your APIs with curl or Postman.
***
## Step 3: Create React Frontend (40 min)
### 3.1 Clone react-flowfull-client (TanStack Start Starter Kit)
::: tip Official Frontend Starter
This tutorial continues with **react-flowfull-client**, the official React starter kit with TanStack Start and `@pubflow/react`.
If you want a Next.js app instead, use **next-flowfull-client** and follow the Next.js examples because the routing and file structure are different.
[View Documentation](https://clients.flowfull.dev/starter-kits)
:::
```bash
# Clone the official React + TanStack Start starter kit
git clone https://github.com/pubflow/react-flowfull-client.git blog-frontend
cd blog-frontend
# Install dependencies
npm install
# or: bun install
```
### 3.2 Configure Environment
Copy the example environment file:
```bash
cp .env.example .env.local
```
Edit `.env.local` with your backend URL:
```env
# API Configuration
VITE_API_BASE_URL=http://localhost:3001
VITE_BRIDGE_BASE_PATH=/bridge
VITE_AUTH_BASE_PATH=/auth
# Branding Configuration (Optional)
VITE_APP_NAME=My Blog
VITE_APP_LOGO=https://your-domain.com/logo.png
VITE_PRIMARY_COLOR=#006aff
VITE_SECONDARY_COLOR=#4a90e2
```
::: info 🔧 Environment Variables
* `VITE_API_BASE_URL`: Your Flowfull backend URL (from Step 2)
* `VITE_BRIDGE_BASE_PATH`: Bridge API path (default: `/bridge`)
* `VITE_AUTH_BASE_PATH`: Auth API path (default: `/auth`)
:::
### 3.3 Create Blog Post List
Create `src/pages/blog.tsx`:
```tsx
import { useBridge } from '@pubflow/react'
import { Link } from '@tanstack/react-router'
export default function BlogPage() {
const { data: posts, loading } = useBridge('/posts')
if (loading) return Loading...
return (
Blog
{posts?.map((post: any) => (
{post.cover_image && (
)}
{post.title}
{post.excerpt}
{new Date(post.created_at).toLocaleDateString()}
{post.premium_only && (
Premium
)}
))}
)
}
```
### 3.4 Create Post Editor
Create `src/pages/editor.tsx`:
```tsx
import { useState } from 'react'
import { useBridge, useAuth } from '@pubflow/react'
import { useNavigate } from '@tanstack/react-router'
export default function EditorPage() {
const { user } = useAuth()
const navigate = useNavigate()
const [title, setTitle] = useState('')
const [content, setContent] = useState('')
const [excerpt, setExcerpt] = useState('')
const [premiumOnly, setPremiumOnly] = useState(false)
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
const response = await fetch(`${import.meta.env.VITE_BRIDGE_URL}/posts`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Session-Id': localStorage.getItem('pubflow_session_id') || ''
},
body: JSON.stringify({
title,
content,
excerpt,
premium_only: premiumOnly
})
})
if (response.ok) {
const { post } = await response.json()
navigate({ to: `/blog/${post.slug}` })
}
}
if (!user) {
return Please login to create posts
}
return (
)
}
```
✅ **Checkpoint:** You can now create and view blog posts!
***
## 💳 Step 4: Add Premium Subscriptions (15 min)
### 4.1 Setup Bridge Payments
1. Go to [Pubflow Dashboard](https://pubflow.com)
2. Create a Bridge Payments instance
3. Configure Stripe:
* Add Stripe API keys
* Create a product: "Premium Subscription"
* Set price: $9.99/month
### 4.2 Create Subscription Page
Create `src/pages/premium.tsx`:
```tsx
import { useAuth } from '@pubflow/react'
import { useState } from 'react'
export default function PremiumPage() {
const { user } = useAuth()
const [loading, setLoading] = useState(false)
const handleSubscribe = async () => {
setLoading(true)
try {
// Create payment intent
const response = await fetch(`${import.meta.env.VITE_PAYMENTS_URL}/intents`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Session-Id': localStorage.getItem('pubflow_session_id') || ''
},
body: JSON.stringify({
total_cents: 999, // $9.99
currency: 'USD',
concept: 'Premium Subscription',
recurring: true,
interval: 'month'
})
})
const { client_secret } = await response.json()
// Redirect to Stripe checkout
// (In production, use Stripe.js for better UX)
window.location.href = `https://checkout.stripe.com/${client_secret}`
} catch (error) {
console.error('Subscription failed:', error)
} finally {
setLoading(false)
}
}
return (
Go Premium
Premium Membership
$9.99/month
✓
Access to all premium articles
✓
Ad-free reading experience
✓
Early access to new content
✓
Support independent writers
{loading ? 'Processing...' : 'Subscribe Now'}
{!user && (
Please login to subscribe
)}
)
}
```
***
## 🚀 Step 5: Deploy (10 min)
### 5.1 Deploy Flowfull Backend
**Option 1: Railway**
```bash
# Install Railway CLI
npm install -g @railway/cli
# Login and deploy
railway login
railway init
railway up
```
**Option 2: Render**
```bash
# Create render.yaml
services:
- type: web
name: blog-backend
env: node
buildCommand: npm install
startCommand: npm start
```
### 5.2 Deploy React Frontend
**Option 1: Vercel**
```bash
# Install Vercel CLI
npm install -g vercel
# Deploy
vercel
```
**Option 2: Netlify**
```bash
# Install Netlify CLI
npm install -g netlify-cli
# Deploy
netlify deploy --prod
```
### 5.3 Update Environment Variables
Update production environment variables:
* Frontend: `VITE_BRIDGE_URL` → your deployed backend URL
* Backend: `BRIDGE_URL` → your Flowless instance URL
***
## 🎉 Result
Congratulations! You've built a complete full-stack blog application using the Pubflow ecosystem.
**What you've accomplished:**
* ✅ User authentication with Flowless
* ✅ Custom backend API with Flowfull
* ✅ Modern React frontend with Flowfull Clients
* ✅ Payment processing with Bridge Payments
* ✅ Production deployment
***
## 🔧 Troubleshooting
### Issue: "Session validation failed"
**Solution:** Make sure your `BRIDGE_SECRET` matches in both frontend and backend.
### Issue: "CORS error"
**Solution:** Add CORS middleware to your Flowfull backend:
```typescript
import { cors } from 'hono/cors'
app.use('/*', cors({
origin: ['http://localhost:5173', 'https://yourdomain.com'],
credentials: true
}))
```
### Issue: "Payment failed"
**Solution:** Check your Stripe API keys and webhook configuration.
***
## 📖 Next Steps
Enhance your blog with:
* 📸 **Image uploads** - Add S3 integration for post images
* 🔍 **Search functionality** - Implement full-text search
* 📊 **Analytics** - Track post views and engagement
* 💬 **Real-time comments** - Use WebSockets for live updates
* 🌐 **Multi-language** - Add i18n support
* 📱 **Mobile app** - Build React Native version
***
## 📚 Related Resources
* 🔐 **[Flowless Documentation](/)** - Learn more about authentication
* ⚡ **[Flowfull Documentation](https://flowfull.dev)** - Backend framework guide
* 🎨 **[Flowfull Clients](https://clients.flowfull.dev)** - Frontend libraries
* 💳 **[Bridge Payments](https://bridgepayments.dev)** - Payment integration
* 💬 **[Discord Community](https://discord.gg/EJfPTT6Vh7)** - Get help and share your project
---
---
url: /examples/mobile-payments.md
---
# 📱 Mobile App with Payments
Build a React Native mobile app with authentication, content, and in-app purchases.
::: info 📖 Cross-Ecosystem Example
This is a **complete tutorial** demonstrating the standard Flowfull architecture pattern using **flowfull-node** for your custom mobile backend.
:::
## 🎯 What You'll Build
A production-ready mobile application with:
* ✅ Social login (Google, Apple)
* ✅ Offline support with local storage
* ✅ Push notifications
* ✅ In-app purchases (Apple Pay / Google Pay)
* ✅ Subscription management
* ✅ Content paywall
* ✅ User profiles with image upload
**Time to complete:** ~120 minutes
**Platforms:** iOS & Android
***
## 🛠️ Tech Stack
| Component | Technology | Purpose |
|-----------|-----------|---------|
| 🔐 **Flowless** | Managed Service (pubflow.com) | Authentication - Social login (Google, Apple), sessions, profiles |
| ⚡ **Flowfull** | Node.js (flowfull-node) | **Your custom backend** - Content API, user data, purchases |
| 🎨 **Flowfull Clients** | React Native (@pubflow/react-native) | **Your mobile app** - Expo with offline support |
| 💳 **Bridge Payments** | Managed Service | Payment processing - In-app purchases, subscriptions |
::: tip 🏗️ Standard Architecture Pattern
* **Flowless** = Authentication backend (managed, no code needed)
* **Flowfull** = Your custom backend using flowfull-node (you write this)
* **Flowfull Clients** = Your mobile app using @pubflow/react-native (you write this)
* **Bridge Payments** = Payment backend (managed, API integration only)
:::
***
## 🏗️ Architecture
```mermaid
graph TB
subgraph "📱 Your Mobile App (React Native)"
A["Login Screen (@pubflow/react-native)"]
B["Content Feed (Expo Components)"]
C["Premium Screen (React Native UI)"]
D["Profile (Image Upload)"]
end
subgraph "⚡ Your Backend (Flowfull)"
E["Content API (flowfull-node)"]
F["User API (Node.js + Database)"]
end
subgraph "☁️ Pubflow Managed Services"
G["🔐 Flowless (pubflow.com)"]
H["💳 Bridge Payments (IAP Processing)"]
end
subgraph "📲 Native Services"
I["Apple Pay"]
J["Google Pay"]
K["Push Notifications"]
end
A -->|"Social Login"| G
B -->|"Fetch Content"| E
C -->|"Purchase"| H
D -->|"Update Profile"| F
E -->|"Validate Sessions"| G
F -->|"Bridge Validation"| G
H -->|"Process Payment"| I
H -->|"Process Payment"| J
style A fill:#4CAF50,stroke:#2E7D32,stroke-width:3px,color:#fff
style E fill:#2196F3,stroke:#1565C0,stroke-width:3px,color:#fff
style G fill:#FF9800,stroke:#E65100,stroke-width:3px,color:#fff
style H fill:#9C27B0,stroke:#6A1B9A,stroke-width:3px,color:#fff
```
**Flow:**
1. Mobile App (React Native) → Your Backend (Flowfull/flowfull-node)
2. Your Backend → Flowless for social authentication
3. Your Backend → Bridge Payments for in-app purchases
4. Bridge Payments → Native payment providers (Apple Pay / Google Pay)
***
## 📋 Prerequisites
* ✅ **Bun** v1.0+ ([Install](https://bun.sh)) or Node.js 18+
* ✅ **Database** - PostgreSQL, MySQL, or LibSQL/Turso
* ✅ **Pubflow account** - Sign up at [pubflow.com](https://pubflow.com)
* ✅ **Expo CLI** - Install with `npm install -g expo-cli`
* ✅ **iOS Simulator** or **Android Emulator**
* ✅ **Apple Developer account** (for iOS in-app purchases)
* ✅ **Google Play Console account** (for Android in-app purchases)
* ✅ Basic knowledge of React Native and TypeScript
***
## 🚀 Step 1: Setup Flowless & Backend (15 min)
### 1.1 Create Flowless Instance
1. Visit [pubflow.com](https://pubflow.com)
2. Sign up or log in
3. Click **"Create Flowless Instance"**
4. Name it: `mobile-auth`
5. Configure OAuth (Google, Apple) for social login
6. Copy your **Bridge Secret**
Your Flowless URL will be:
```
https://mobile-auth.pubflow.com
```
::: tip 📖 Learn More
For detailed Flowless setup, see [Flowless Getting Started](https://flowless.dev/getting-started)
:::
### 1.2 Setup Flowfull Backend
::: tip 📦 Official Starter Kit
**flowfull-node** is the official, production-ready starter kit maintained by the Pubflow team.
[View Documentation →](https://flowfull.dev/getting-started)
:::
```bash
# Clone the official flowfull-node template
git clone https://github.com/pubflow/flowfull-node.git mobile-backend
cd mobile-backend
# Install dependencies
bun install
# or: npm install
# Configure environment
cp .env.example .env
```
Edit `.env`:
```env
# Flowless Configuration
FLOWLESS_API_URL=https://mobile-auth.pubflow.com
BRIDGE_VALIDATION_SECRET=your_bridge_secret_here
# Database
DATABASE_URL=postgresql://user:pass@localhost:5432/mobile
# Server
PORT=3001
NODE_ENV=development
# Optional: Cache
REDIS_URL=redis://localhost:6379
```
***
## 📱 Step 2: Setup React Native App (15 min)
### 2.1 Clone create-pubflow-rn (Official Starter Kit)
::: tip 📱 Official Mobile Starter
**create-pubflow-rn** is the official React Native Expo starter kit with complete authentication, offline support, and native components.
[View Documentation →](https://clients.flowfull.dev/starter-kits)
:::
```bash
# Clone the official React Native Expo starter kit
git clone https://github.com/pubflow/create-pubflow-rn.git my-app
cd my-app
# Install dependencies
npm install
# or: bun install
```
### 2.2 Configure Environment
Copy the example environment file:
```bash
cp .env.example .env
```
Edit `.env`:
```env
# API Configuration
EXPO_PUBLIC_BRIDGE_URL=http://localhost:3001
EXPO_PUBLIC_API_BASE_URL=http://localhost:3001
# Branding (Optional)
EXPO_PUBLIC_APP_NAME=My App
EXPO_PUBLIC_PRIMARY_COLOR=#006aff
```
::: info 🔧 Environment Variables
* `EXPO_PUBLIC_BRIDGE_URL`: Your Flowfull backend URL from Step 1.2
* `EXPO_PUBLIC_API_BASE_URL`: Same as BRIDGE\_URL for API calls
:::
### 1.3 Install Dependencies
```bash
# Payment processing
npx expo install expo-apple-authentication
npx expo install @react-native-google-signin/google-signin
# Push notifications
npx expo install expo-notifications
# Image picker
npx expo install expo-image-picker
```
***
## 🔐 Step 2: Social Authentication (20 min)
### 2.1 Login Screen
```tsx
// app/login.tsx
import { useState } from 'react'
import { View, Text, TouchableOpacity } from 'react-native'
import { useAuth } from '@pubflow/react-native'
import * as AppleAuthentication from 'expo-apple-authentication'
import { GoogleSignin } from '@react-native-google-signin/google-signin'
export default function LoginScreen() {
const { login, loginWithOAuth } = useAuth()
const [loading, setLoading] = useState(false)
const handleAppleLogin = async () => {
try {
const credential = await AppleAuthentication.signInAsync({
requestedScopes: [
AppleAuthentication.AppleAuthenticationScope.FULL_NAME,
AppleAuthentication.AppleAuthenticationScope.EMAIL,
],
})
await loginWithOAuth('apple', {
id_token: credential.identityToken,
user: credential.user
})
} catch (error) {
console.error('Apple login failed:', error)
}
}
const handleGoogleLogin = async () => {
try {
await GoogleSignin.hasPlayServices()
const userInfo = await GoogleSignin.signIn()
await loginWithOAuth('google', {
id_token: userInfo.idToken
})
} catch (error) {
console.error('Google login failed:', error)
}
}
return (
Welcome
Continue with Google
)
}
```
***
## 📱 Step 3: Content Feed (25 min)
### 3.1 Content API
```typescript
// backend/src/routes/content.ts
import { Hono } from 'hono'
import { validateSession } from '../middleware/auth'
const content = new Hono()
content.get('/', async (c) => {
const sessionId = c.req.header('X-Session-Id')
let isPremium = false
if (sessionId) {
const user = await validateUserSession(sessionId)
isPremium = user?.is_premium || false
}
const posts = await db
.selectFrom('posts')
.selectAll()
.where('published', '=', true)
.where((eb) =>
isPremium
? eb.or([eb('premium_only', '=', false), eb('premium_only', '=', true)])
: eb('premium_only', '=', false)
)
.execute()
return c.json({ posts, is_premium: isPremium })
})
export default content
```
### 3.2 Feed Screen
```tsx
// app/(tabs)/feed.tsx
import { FlatList, View, Text, Image, TouchableOpacity } from 'react-native'
import { useBridge, useAuth } from '@pubflow/react-native'
import { router } from 'expo-router'
export default function FeedScreen() {
const { user } = useAuth()
const { data: content } = useBridge('/content')
const renderPost = ({ item }: any) => (
router.push(`/post/${item.id}`)}
className="bg-white rounded-lg mb-4 overflow-hidden shadow"
>
{item.cover_image && (
)}
{item.title}
{item.excerpt}
{item.premium_only && !user?.is_premium && (
🔒 Premium Content
)}
)
return (
item.id}
contentContainerStyle={{ padding: 16 }}
/>
)
}
```
***
## 💳 Step 4: In-App Purchases (30 min)
### 4.1 Premium Screen
```tsx
// app/(tabs)/premium.tsx
import { View, Text, TouchableOpacity, Alert } from 'react-native'
import { useAuth } from '@pubflow/react-native'
import AsyncStorage from '@react-native-async-storage/async-storage'
export default function PremiumScreen() {
const { user } = useAuth()
const handleSubscribe = async () => {
try {
const sessionId = await AsyncStorage.getItem('pubflow_session_id')
// Create payment intent
const response = await fetch(`${process.env.EXPO_PUBLIC_PAYMENTS_URL}/intents`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Session-Id': sessionId || ''
},
body: JSON.stringify({
total_cents: 999, // $9.99
currency: 'USD',
concept: 'Premium Subscription',
recurring: true,
interval: 'month',
payment_method: 'apple_pay' // or 'google_pay'
})
})
const { client_secret } = await response.json()
// Process payment with native payment sheet
// Implementation depends on payment provider
Alert.alert('Success', 'Welcome to Premium!')
} catch (error) {
Alert.alert('Error', 'Subscription failed')
}
}
if (user?.is_premium) {
return (
You're Premium! 🎉
Enjoy unlimited access to all content
)
}
return (
Go Premium
$9.99
per month
✓
Unlimited access to all content
✓
Ad-free experience
✓
Offline downloads
✓
Early access to new features
Subscribe Now
)
}
```
***
## 🔔 Step 5: Push Notifications (15 min)
```tsx
// utils/notifications.ts
import * as Notifications from 'expo-notifications'
import { Platform } from 'react-native'
export async function registerForPushNotifications() {
const { status: existingStatus } = await Notifications.getPermissionsAsync()
let finalStatus = existingStatus
if (existingStatus !== 'granted') {
const { status } = await Notifications.requestPermissionsAsync()
finalStatus = status
}
if (finalStatus !== 'granted') {
return null
}
const token = await Notifications.getExpoPushTokenAsync()
// Send token to backend
await fetch(`${process.env.EXPO_PUBLIC_BRIDGE_URL}/notifications/register`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token: token.data })
})
return token.data
}
```
***
## 🎉 Result
You've built a complete mobile app with:
* ✅ Social authentication
* ✅ Content feed
* ✅ In-app purchases
* ✅ Push notifications
***
## 📖 Next Steps
* 📥 **Offline mode** - Cache content locally
* 🎨 **Dark mode** - Theme support
* 🌍 **Localization** - Multi-language
* 📊 **Analytics** - Track user behavior
***
## 📚 Related Resources
* 🔐 **[Flowless](/)** - Authentication
* ⚡ **[Flowfull](https://flowfull.dev)** - Backend
* 💳 **[Bridge Payments](https://bridgepayments.dev)** - Payments
* 💬 **[Discord](https://discord.gg/EJfPTT6Vh7)** - Community
---
---
url: /examples/ecommerce-store.md
---
# 🛒 E-commerce Store
Build a complete online store with product catalog, shopping cart, and secure checkout.
::: info 📖 Cross-Ecosystem Example
This is a **complete tutorial** demonstrating the standard Flowfull architecture pattern using **flowfull-node** for your custom e-commerce backend.
:::
## 🎯 What You'll Build
A production-ready e-commerce platform with:
* ✅ Product catalog with categories and search
* ✅ Shopping cart (guest + authenticated)
* ✅ Secure checkout with Stripe & PayPal
* ✅ Order management and history
* ✅ Saved payment methods
* ✅ Inventory management
* ✅ Admin dashboard
* ✅ Email notifications
**Time to complete:** ~120 minutes
***
## 🛠️ Tech Stack
| Component | Technology | Purpose |
|-----------|-----------|---------|
| 🔐 **Flowless** | Managed Service (pubflow.com) | Authentication - User accounts, guest checkout |
| ⚡ **Flowfull** | Node.js (flowfull-node) | **Your custom backend** - Products, orders, inventory APIs |
| 🎨 **Flowfull Clients** | Next.js (@pubflow/nextjs) | **Your frontend** - Storefront with SSR |
| 💳 **Bridge Payments** | Managed Service | Payment processing - Stripe, PayPal, saved cards |
::: tip 🏗️ Standard Architecture Pattern
* **Flowless** = Authentication backend (managed, no code needed)
* **Flowfull** = Your custom backend using flowfull-node (you write this)
* **Flowfull Clients** = Your frontend using @pubflow/nextjs (you write this)
* **Bridge Payments** = Payment backend (managed, API integration only)
:::
***
## 🏗️ Architecture
```mermaid
graph TB
subgraph "🎨 Your Frontend (Next.js)"
A["Product Catalog (@pubflow/nextjs)"]
B["Shopping Cart (Next.js SSR)"]
C["Checkout (Bridge Payments UI)"]
D["Order History (React Components)"]
end
subgraph "⚡ Your Backend (Flowfull)"
E["Products API (flowfull-node)"]
F["Orders API (Node.js + Database)"]
G["Inventory API (Custom Business Logic)"]
end
subgraph "☁️ Pubflow Managed Services"
H["🔐 Flowless (pubflow.com)"]
I["💳 Bridge Payments (Payment Processing)"]
end
A -->|"Fetch Products"| E
B -->|"Update Cart"| E
C -->|"Process Payment"| I
D -->|"Get Orders"| F
E -->|"Validate Sessions"| H
F -->|"Bridge Validation"| H
F -->|"Payment Webhooks"| I
style A fill:#4CAF50,stroke:#2E7D32,stroke-width:3px,color:#fff
style E fill:#2196F3,stroke:#1565C0,stroke-width:3px,color:#fff
style H fill:#FF9800,stroke:#E65100,stroke-width:3px,color:#fff
style I fill:#9C27B0,stroke:#6A1B9A,stroke-width:3px,color:#fff
```
**Flow:**
1. Frontend (Next.js) → Your Backend (Flowfull/flowfull-node)
2. Your Backend → Flowless for authentication
3. Your Backend → Bridge Payments for payment processing
4. Bridge Payments → Your Backend (webhooks for order confirmation)
***
## 📋 Prerequisites
* ✅ **Bun** v1.0+ ([Install](https://bun.sh)) or Node.js 18+
* ✅ **Database** - PostgreSQL, MySQL, or LibSQL/Turso
* ✅ **Pubflow account** - Sign up at [pubflow.com](https://pubflow.com)
* ✅ **Stripe account** - Sign up at [stripe.com](https://stripe.com)
* ✅ **Code Editor** - VS Code, Cursor, or your favorite editor
* ✅ Basic knowledge of React and TypeScript
***
## 🚀 Step 1: Setup Services (10 min)
### 1.1 Create Flowless Instance
1. Visit [pubflow.com](https://pubflow.com)
2. Sign up or log in
3. Click **"Create Flowless Instance"**
4. Name it: `store-auth`
5. Enable guest accounts for guest checkout
6. Configure OAuth (Google, Facebook) for social login
7. Copy your **Bridge Secret**
Your Flowless URL will be:
```
https://store-auth.pubflow.com
```
::: tip 📖 Learn More
For detailed Flowless setup, see [Flowless Getting Started](https://flowless.dev/getting-started)
:::
### 1.2 Create Bridge Payments Instance
1. Create Bridge Payments instance at [pubflow.com](https://pubflow.com)
2. Add Stripe credentials
3. Add PayPal credentials (optional)
4. Configure webhooks
5. Copy your **Bridge Payments URL** and **API Key**
***
## ⚡ Step 2: Setup Flowfull Backend (10 min)
### 2.1 Clone flowfull-node (Official Starter Kit)
::: tip 📦 Official Starter Kit
**flowfull-node** is the official, production-ready starter kit maintained by the Pubflow team.
[View Documentation →](https://flowfull.dev/getting-started)
:::
```bash
# Clone the official flowfull-node template
git clone https://github.com/pubflow/flowfull-node.git store-backend
cd store-backend
# Install dependencies
bun install
# or: npm install
```
### 2.2 Configure Environment Variables
Copy the example environment file:
```bash
cp .env.example .env
```
Edit `.env` with your configuration:
```env
# Flowless Configuration
FLOWLESS_API_URL=https://store-auth.pubflow.com
BRIDGE_VALIDATION_SECRET=your_bridge_secret_here
# Database
DATABASE_URL=postgresql://user:pass@localhost:5432/store
# Stripe (via Bridge Payments)
STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...
# Bridge Payments
BRIDGE_PAYMENTS_URL=https://your-payments.pubflow.com
BRIDGE_PAYMENTS_API_KEY=your_api_key_here
# Server
PORT=3001
NODE_ENV=development
# Optional: Cache
REDIS_URL=redis://localhost:6379
```
::: info 🔧 Environment Variables
* `FLOWLESS_API_URL`: Your Flowless instance URL from Step 1.1
* `BRIDGE_VALIDATION_SECRET`: Bridge secret from Pubflow dashboard
* `STRIPE_SECRET_KEY`: Your Stripe secret key from [Stripe Dashboard](https://dashboard.stripe.com/apikeys)
* `BRIDGE_PAYMENTS_URL`: Your Bridge Payments instance URL from Step 1.2
:::
***
## 📊 Step 3: Database Schema (15 min)
Create `schema.sql`:
```sql
-- Products
CREATE TABLE products (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name VARCHAR(500) NOT NULL,
slug VARCHAR(500) UNIQUE NOT NULL,
description TEXT,
price_cents INTEGER NOT NULL,
compare_at_price_cents INTEGER,
images JSONB DEFAULT '[]',
category VARCHAR(100),
stock INTEGER DEFAULT 0,
sku VARCHAR(100) UNIQUE,
active BOOLEAN DEFAULT true,
created_at TIMESTAMP DEFAULT NOW()
);
-- Orders
CREATE TABLE orders (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id VARCHAR(255),
guest_token VARCHAR(255),
status VARCHAR(50) DEFAULT 'pending',
total_cents INTEGER NOT NULL,
currency VARCHAR(3) DEFAULT 'USD',
payment_intent_id VARCHAR(255),
shipping_address JSONB,
billing_address JSONB,
items JSONB NOT NULL,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
-- Order Items
CREATE TABLE order_items (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
order_id UUID REFERENCES orders(id) ON DELETE CASCADE,
product_id UUID REFERENCES products(id),
quantity INTEGER NOT NULL,
price_cents INTEGER NOT NULL,
product_snapshot JSONB
);
-- Cart (for authenticated users)
CREATE TABLE cart_items (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id VARCHAR(255) NOT NULL,
product_id UUID REFERENCES products(id) ON DELETE CASCADE,
quantity INTEGER NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
-- Indexes
CREATE INDEX IF NOT EXIST idx_products_category ON products(category);
CREATE INDEX IF NOT EXIST idx_products_slug ON products(slug);
CREATE INDEX IF NOT EXIST idx_orders_user_id ON orders(user_id);
CREATE INDEX IF NOT EXIST idx_orders_guest_token ON orders(guest_token);
CREATE INDEX IF NOT EXIST idx_cart_user_id ON cart_items(user_id);
```
***
## 🎨 Step 3: Product Catalog API (20 min)
Create `src/routes/products.ts`:
```typescript
import { Hono } from 'hono'
import { db } from '../db'
const products = new Hono()
// Get all products
products.get('/', async (c) => {
const category = c.req.query('category')
const search = c.req.query('search')
let query = db
.selectFrom('products')
.selectAll()
.where('active', '=', true)
if (category) {
query = query.where('category', '=', category)
}
if (search) {
query = query.where('name', 'ilike', `%${search}%`)
}
const products = await query
.orderBy('created_at', 'desc')
.execute()
return c.json({ products })
})
// Get single product
products.get('/:slug', async (c) => {
const slug = c.req.param('slug')
const product = await db
.selectFrom('products')
.selectAll()
.where('slug', '=', slug)
.where('active', '=', true)
.executeTakeFirst()
if (!product) {
return c.json({ error: 'Product not found' }, 404)
}
return c.json({ product })
})
export default products
```
***
## 🛒 Step 4: Shopping Cart & Checkout (30 min)
### 4.1 Cart API
```typescript
// src/routes/cart.ts
import { Hono } from 'hono'
import { validateSession } from '../middleware/auth'
const cart = new Hono()
// Get cart
cart.get('/', validateSession, async (c) => {
const user = c.get('user')
const items = await db
.selectFrom('cart_items')
.innerJoin('products', 'products.id', 'cart_items.product_id')
.selectAll()
.where('cart_items.user_id', '=', user.id)
.execute()
const total = items.reduce((sum, item) =>
sum + (item.price_cents * item.quantity), 0
)
return c.json({ items, total_cents: total })
})
// Add to cart
cart.post('/add', validateSession, async (c) => {
const user = c.get('user')
const { product_id, quantity } = await c.req.json()
await db
.insertInto('cart_items')
.values({ user_id: user.id, product_id, quantity })
.onConflict((oc) => oc
.column('user_id')
.column('product_id')
.doUpdateSet({ quantity: (eb) => eb.ref('quantity') + quantity })
)
.execute()
return c.json({ success: true })
})
```
### 4.2 Checkout with Bridge Payments
```typescript
// src/routes/checkout.ts
import { Hono } from 'hono'
import { validateSession } from '../middleware/auth'
const checkout = new Hono()
checkout.post('/', validateSession, async (c) => {
const user = c.get('user')
const { shipping_address, billing_address } = await c.req.json()
// Get cart items
const items = await db
.selectFrom('cart_items')
.innerJoin('products', 'products.id', 'cart_items.product_id')
.selectAll()
.where('cart_items.user_id', '=', user.id)
.execute()
const total_cents = items.reduce((sum, item) =>
sum + (item.price_cents * item.quantity), 0
)
// Create payment intent with Bridge Payments
const paymentResponse = await fetch(`${process.env.PAYMENTS_URL}/intents`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Session-Id': c.req.header('X-Session-Id') || ''
},
body: JSON.stringify({
total_cents,
currency: 'USD',
concept: 'Order Payment',
metadata: { user_id: user.id }
})
})
const { client_secret, intent_id } = await paymentResponse.json()
// Create order
const order = await db
.insertInto('orders')
.values({
user_id: user.id,
total_cents,
payment_intent_id: intent_id,
shipping_address,
billing_address,
items: JSON.stringify(items),
status: 'pending'
})
.returningAll()
.executeTakeFirst()
return c.json({ order, client_secret })
})
```
***
## 🎨 Step 5: Next.js Frontend (40 min)
### 5.1 Product Listing Page
```tsx
// app/products/page.tsx
import { PubflowProvider } from '@pubflow/nextjs'
export default async function ProductsPage() {
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/products`)
const { products } = await res.json()
return (
{products.map((product: any) => (
{product.name}
{product.description}
${(product.price_cents / 100).toFixed(2)}
Add to Cart
))}
)
}
```
### 5.2 Checkout Page
```tsx
// app/checkout/page.tsx
'use client'
import { useState } from 'react'
import { useAuth } from '@pubflow/react'
export default function CheckoutPage() {
const { user } = useAuth()
const [loading, setLoading] = useState(false)
const handleCheckout = async () => {
setLoading(true)
const response = await fetch('/api/checkout', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Session-Id': localStorage.getItem('pubflow_session_id') || ''
},
body: JSON.stringify({
shipping_address: {
street: '123 Main St',
city: 'New York',
state: 'NY',
zip: '10001'
}
})
})
const { client_secret } = await response.json()
// Redirect to Stripe checkout
window.location.href = `https://checkout.stripe.com/${client_secret}`
}
return (
Checkout
{/* Cart summary */}
{/* Shipping form */}
{/* Payment button */}
{loading ? 'Processing...' : 'Complete Purchase'}
)
}
```
***
## 🚀 Step 6: Deploy & Test
### Deploy Backend
```bash
railway up
```
### Deploy Frontend
```bash
vercel --prod
```
***
## 🎉 Result
You've built a complete e-commerce store with:
* ✅ Product catalog with search
* ✅ Shopping cart functionality
* ✅ Secure checkout with Stripe
* ✅ Order management
* ✅ User authentication
***
## 📖 Next Steps
* 📧 **Email notifications** - Order confirmations
* 📦 **Shipping integration** - Real-time tracking
* ⭐ **Product reviews** - Customer feedback
* 🎁 **Discount codes** - Promotional campaigns
* 📊 **Analytics** - Sales dashboard
***
## 📚 Related Resources
* 🔐 **[Flowless Documentation](/)** - Authentication guide
* ⚡ **[Flowfull Documentation](https://flowfull.dev)** - Backend framework
* 💳 **[Bridge Payments](https://bridgepayments.dev)** - Payment integration
* 💬 **[Discord Community](https://discord.gg/EJfPTT6Vh7)** - Get help
---
---
url: /api/two-factor.md
---
# 2FA API
The Two-Factor Authentication API adds a second verification step to the login flow and to related session-sensitive actions.
The goal is simple: keep authentication easy for users while making account access safer for developers and product teams.
## How to read this page
Each route is documented as a normal operation-style page so the flow is easy to follow.
## Base path
All routes live under `/auth/two_factor/`.
## How it works
1. The user logs in with password or social auth.
2. If 2FA is required, the server creates a short-lived pending session.
3. The server sends a 6-digit numeric code by email.
4. The client submits the code to the verify route.
5. The session is promoted to active after successful verification.
## Route map
| Method | Path | Auth | Purpose |
|--------|------|------|---------|
| `GET` | `/auth/two_factor/system` | Public | Check whether 2FA is enabled and which methods are available |
| `GET` | `/auth/two_factor/methods` | Session | List the user’s active 2FA methods |
| `POST` | `/auth/two_factor/email/setup` | Session | Start email 2FA setup |
| `POST` | `/auth/two_factor/sms/setup` | Session | Start SMS 2FA setup |
| `POST` | `/auth/two_factor/:method/start` | Pending or active session | Resend a code for a method |
| `POST` | `/auth/two_factor/verify` | Pending or active session | Verify a code and activate the session |
| `DELETE` | `/auth/two_factor/:id` | Session | Remove a method |
| `POST` | `/auth/two_factor/toggle` | Session | Enable or disable 2FA for the user |
## Route details
### System and methods
#### `GET /auth/two_factor/system`
Return global availability and method list.
Auth: public.
#### `GET /auth/two_factor/methods`
List the current user’s active methods.
Auth: session.
### Setup
#### `POST /auth/two_factor/email/setup`
Start email 2FA setup.
Auth: session.
#### `POST /auth/two_factor/sms/setup`
Start SMS 2FA setup.
Auth: session.
### Verification flow
#### `POST /auth/two_factor/:method/start`
Resend a code for a method.
Auth: pending or active session.
Body:
```json
{
"action": "login"
}
```
#### `POST /auth/two_factor/verify`
Verify a code and activate the session.
Auth: pending or active session.
Body:
```json
{
"code": "482913",
"method": "email",
"action": "login"
}
```
### Maintenance
#### `DELETE /auth/two_factor/:id`
Remove a method.
Auth: session.
#### `POST /auth/two_factor/toggle`
Enable or disable 2FA for the user.
Auth: session.
Body: `{ "two_factor_enabled": false, "verification_code": "123456", "verification_method_id": "..." }`.
When disabling and the user has active methods, `verification_code` and `verification_method_id` are required. Do not send `two_factor` on `PUT /auth/user/me`.
## Example: check system availability
```http
GET /auth/two_factor/system
```
Example response:
```json
{
"success": true,
"data": {
"global_two_factor_enabled": true,
"available_methods": ["email"]
}
}
```
## Example: start a login challenge
```http
POST /auth/two_factor/email/start
Content-Type: application/json
{
"action": "login"
}
```
Example response:
```json
{
"success": true,
"data": {
"method": "email",
"status": "pending",
"expires_in_seconds": 600
}
}
```
## Example: verify a code
```http
POST /auth/two_factor/verify
Content-Type: application/json
{
"code": "482913",
"method": "email",
"action": "login"
}
```
Example response:
```json
{
"success": true,
"data": {
"verified": true,
"session_status": "active",
"two_factor_verified": 1
}
}
```
## Important behavior
* The code is 6 digits and numeric.
* The code is treated as short-lived and must be verified within the session window.
* A pending session is not the final session; it becomes active only after verification.
* The flow is meant to be understandable to the frontend, not hidden behind vague auth behavior.
## Typical login flow
1. User submits credentials.
2. Server returns a 2FA challenge instead of a full login session.
3. User enters the code from email.
4. Client submits the code to verify.
5. Server activates the session and returns success.
## Practical notes
* Keep login and verification steps separate in the UI.
* Treat the pending session as a temporary state, not a broken login.
* Make the 2FA screen explicit so developers can reason about it quickly.
## Next
* [Modules overview](/modules/index)
* [Module Hub API](/api/module-hub)
* [Blog API](/api/blog)
---
---
url: /operations/twoFactorMethods.md
---
---
---
url: /modules/two-factor.md
---
# 2FA Module
The 2FA module adds an extra account security step during login.
Current implementation is code-based verification, focused on predictable login flows.
## Core vs Extensions
| Area | Type | Required to use 2FA? | Notes |
|------|------|----------------------|-------|
| System status (`/system`) | Core | Yes | Reads global toggle + available methods |
| User methods (`/methods`) | Core | Yes | Reads configured user methods |
| Start challenge (`/{method}/start`) | Core | Yes | Sends verification code |
| Verify (`/verify`) | Core | Yes | Promotes pending session to active (login flow) |
| Setup endpoints (`/email/setup`, `/sms/setup`) | Core | Yes | Method provisioning |
| Toggle and delete method | Core | Yes | Account-level control |
| Optional extensions | Extension | No | No separate 2FA extension pack documented right now |
## Important note
Unlike Blog, 2FA does not currently expose a separate optional extension family in docs.
So today, 2FA is treated as one cohesive module. You enable it as a capability, not as multiple plugin packs.
## Read the API docs
* [2FA operations](/operations/modules/two-factor)
* [Module Hub operations](/operations/modules/module-hub)
* [Blog module](/modules/blog)
---
---
url: /operations/modules/two-factor.md
---
# 2FA Operations
Individual operation pages for the Two-Factor Authentication module live under `operations/` and are grouped here for easy navigation.
## Routes
* [2FA System](/operations/twoFactorSystem)
* [2FA Methods](/operations/twoFactorMethods)
* [Start Email 2FA Setup](/operations/twoFactorEmailSetup)
* [Start SMS 2FA Setup](/operations/twoFactorSmsSetup)
* [Start 2FA Challenge](/operations/twoFactorStart)
* [Verify 2FA Code](/operations/twoFactorVerify)
* [Delete 2FA Method](/operations/twoFactorDelete)
* [Toggle 2FA](/operations/twoFactorToggle)
---
---
url: /operations/twoFactorSystem.md
---
---
---
url: /operations/adminAcquisitionAnalytics.md
---
Acquisition breakdown by channel or source.
Path: `GET /auth/admin/analytics/acquisition`\
Auth: admin / superadmin session.\
Query: `group_by=channel|source`, optional `from` / `to` (on `acquisition_at`).\
Requires onboarding **core** columns. `404 module_not_installed` otherwise.
Related: [Admin acquisition funnel](/operations/adminAcquisitionFunnel) · [Onboarding operations](/operations/modules/onboarding) · [Admin API](/api/admin)
---
---
url: /operations/adminAcquisitionFunnel.md
---
Per-source funnel: `count`, `verified_count`, `converted_count` (`first_time=false`).
Path: `GET /auth/admin/analytics/acquisition/funnel`\
Auth: admin / superadmin session.\
Query: optional `channel` filter.\
Requires onboarding **core** columns.
Related: [Admin acquisition analytics](/operations/adminAcquisitionAnalytics) · [Onboarding operations](/operations/modules/onboarding)
---
---
url: /api/admin.md
---
# Admin API
Admin routes under the **`/auth`** mount.
## User management
| Method | Path | Notes |
|--------|------|-------|
| `GET` | `/auth/users` | List/search + onboarding filters |
| `POST` | `/auth/register` | Admin create user |
| `DELETE` | `/auth/users/:user_id` | Admin delete user |
| `GET` | `/auth/admin/users/:id` | Get user + sessions (biz + privacy; no acquisition) |
| `PUT` | `/auth/admin/users/:id` | Update core profile / type |
| `POST` | `/auth/password-change/admin` | Admin password change |
| `PATCH` | `/auth/admin/users/:id/privacy` | Privacy override (admin/superadmin) |
## Privacy / acquisition analytics (onboarding module)
Requires **admin** or **superadmin** session. Part of the privacy/onboarding module (core + acquisition columns). **Not** gated by `USER_ANALYTICS_MCU`.
| Method | Path | Notes |
|--------|------|-------|
| `GET` | `/auth/admin/analytics/acquisition` | Channel/source breakdown |
| `GET` | `/auth/admin/analytics/acquisition/funnel` | Per-source funnel |
## User analytics (MCU opt-in)
Requires `USER_ANALYTICS_ENABLED=true` or `USER_ANALYTICS_MCU=user-analytics://enabled@...`.\
Default roles: `admin,superadmin` (CSV via MCU). Aggregates only — **no PII**. Uses `getKyselyDb` (multi-dialect). Separate from privacy/acquisition analytics above.
```bash
USER_ANALYTICS_MCU=user-analytics://enabled@config/v1?roles=admin,superadmin&features=summary,breakdown,age,metrics,cohorts,crosstab,query,compare,completeness,churn,lifecycle,security
```
| Method | Path | Notes |
|--------|------|-------|
| `GET` | `/auth/admin/analytics/users/summary` | KPIs + `avg_age`; `compare=previous` |
| `GET` | `/auth/admin/analytics/users/breakdown` | `dimension=` allowlist |
| `GET` | `/auth/admin/analytics/users/age` | Age ranges + avg |
| `GET` | `/auth/admin/analytics/users/metrics` | `metrics=` CSV |
| `GET` | `/auth/admin/analytics/users/cohorts` | Signup cohorts |
| `GET` | `/auth/admin/analytics/users/crosstab` | `row=` × `col=` |
| `GET` | `/auth/admin/analytics/users/query` | Orquestrator `view=` |
| `GET` | `/auth/admin/analytics/users/completeness` | Profile field fill rates |
| `GET` | `/auth/admin/analytics/users/churn` | Soft-delete aggregates |
| `GET` | `/auth/admin/analytics/users/lifecycle` | registered → verified → onboarded |
Shared filters: `from`, `to`, `user_type`, `user_types`, `lang`, `gender`, `title`, flags, `include_deleted`.
Disabled MCU → `503 MODULE_DISABLED`. Rate limit Ultra (default 60/10min).
## Operations
* [List users](/operations/adminListUsers)
* [Acquisition analytics](/operations/adminAcquisitionAnalytics)
* [User analytics summary](/operations/adminUserAnalyticsSummary)
* [Onboarding operations](/operations/modules/onboarding)
## Next Steps
* [Users API](/api/users)
* [Module Hub operations](/operations/modules/module-hub)
---
---
url: /operations/adminPatchUserPrivacy.md
---
Admin override of privacy fields for a user.
Path: `PATCH /auth/admin/users/:id/privacy`\
Auth: admin / superadmin session.\
Body (strict, at least one field): `privacy_region`, `gdpr_consent`, `gdpr_consent_version`, `ccpa_applies`, `ccpa_opt_out`.\
Requires **ext-privacy**. `400 module_not_installed` otherwise.
User self-service remains under [Privacy operations](/operations/modules/privacy).
Related: [Admin get user](/operations/adminGetUser) · [Privacy operations](/operations/modules/privacy)
---
---
url: /operations/adminUserAnalyticsQuery.md
---
Multipurpose orchestrator: `view=summary|breakdown|age|metrics|cohorts|crosstab|completeness|churn|lifecycle`.
Path: `GET /auth/admin/analytics/users/query`\
Auth: session with MCU-allowed role. Aggregates only (no PII).
Related: [Admin API](/api/admin) · [Summary](/operations/adminUserAnalyticsSummary)
---
---
url: /operations/adminUserAnalyticsSummary.md
---
KPIs for users (aggregates only). Requires `USER_ANALYTICS` MCU enabled.
Path: `GET /auth/admin/analytics/users/summary`\
Query: shared filters + optional `compare=previous` (needs `from`/`to`).
Related: [Admin API](/api/admin) · [User analytics query](/operations/adminUserAnalyticsQuery)
---
---
url: /monitoring/alerts.md
---
# Alerts
::: warning COMING SOON
This page is under construction. Check back soon for complete documentation.
:::
Configure alerts and notifications for your Flowless instance.
## Overview
This page will cover:
* Alert types
* Alert configuration
* Notification channels
* Alert thresholds
* Alert history
***
## Coming Soon
Comprehensive alerts guide covering:
* Error rate alerts
* Performance alerts
* Usage limit alerts
* Security alerts
* Custom alert rules
***
## Next Steps
* [**Dashboard**](/monitoring/dashboard) - Dashboard overview
* [**Analytics**](/monitoring/analytics) - Analytics and insights
* [**Logs**](/monitoring/logs) - View logs
---
---
url: /monitoring/analytics.md
---
# Analytics
::: warning COMING SOON
This page is under construction. Check back soon for complete documentation.
:::
Detailed analytics and insights for your Flowless instance.
## Overview
This page will cover:
* User analytics
* Authentication analytics
* API usage analytics
* Performance metrics
* Custom reports
***
## Coming Soon
Comprehensive analytics guide covering:
* User growth metrics
* Authentication success rates
* API endpoint usage
* Performance trends
* Export and reporting
***
## Next Steps
* [**Dashboard**](/monitoring/dashboard) - Dashboard overview
* [**Logs**](/monitoring/logs) - View logs
* [**Alerts**](/monitoring/alerts) - Configure alerts
---
---
url: /playground.md
---
# 🎮 Interactive API Playground
Test all Flowless authentication endpoints with a **fully interactive playground**. Try requests directly from your browser!
::: tip 📖 Live API Testing
All endpoints are interactive with real-time request/response testing. Change parameters, headers, and body content to see how the API responds.
:::
::: info � Quick Start
1. Select an endpoint from the list below
2. Fill in the required parameters
3. Click "Try it out" to send the request
4. View the response in real-time
:::
***
***
## 📚 Additional Resources
::: tip 💡 Need More Help?
* 📖 **[Complete API Reference](/api/authentication)** - Detailed documentation with Scalar
* 🎨 **[Flowfull Clients](https://clients.flowfull.dev)** - Pre-built UI components and SDKs
* 🚀 **[Getting Started Guide](/getting-started)** - Set up your first instance
* 💬 **[Discord Community](https://discord.gg/EJfPTT6Vh7)** - Get help from the community
:::
::: info 🔧 Alternative Testing Tools
You can also use these popular API clients:
* **[Postman](https://www.postman.com/)** - Full-featured API client
* **[Insomnia](https://insomnia.rest/)** - Simple and elegant
* **[Thunder Client](https://www.thunderclient.com/)** - VS Code extension
* **[HTTPie](https://httpie.io/)** - Command-line HTTP client
:::
---
---
url: /api/social-login-api.md
---
---
---
url: /operations/socialLoginApi.md
---
---
---
url: /architecture.md
---
# Architecture
Understanding the Flowless architecture will help you design better integrations and make informed decisions about your application's structure.
***
## System Overview
Flowless is part of the larger **Pubflow ecosystem**, which consists of three main components:
```mermaid
graph TB
subgraph "🎨 Your Application"
A["🌐 Frontend React, Next.js, React Native"]
B["⚡ Backend - Flowfull Your Business Logic"]
end
subgraph "☁️ Pubflow Managed Services"
C["🔐 Flowless Authentication Service"]
D["📊 Pubflow Dashboard Management & Monitoring"]
end
A -->|"1️⃣ Auth Requests (login, register)"| C
A -->|"2️⃣ API Requests + session_id"| B
B -->|"3️⃣ Validate Session + bridge_secret"| C
C -->|"4️⃣ Trust Token + user data"| B
B -->|"5️⃣ Protected Data (authorized)"| A
D -->|"⚙️ Manage & Monitor"| C
style A fill:#4CAF50,stroke:#2E7D32,stroke-width:3px,color:#fff
style B fill:#2196F3,stroke:#1565C0,stroke-width:3px,color:#fff
style C fill:#FF9800,stroke:#E65100,stroke-width:3px,color:#fff
style D fill:#9C27B0,stroke:#6A1B9A,stroke-width:3px,color:#fff
```
### Components
1. **🎨 Frontend - Flowfull Clients** (Your Code)
* **Technology**: React, Next.js, React Native using @pubflow/react, @pubflow/nextjs, or @pubflow/react-native
* **Purpose**: User interface and interactions
* **What you build**: Your app's UI, forms, navigation
* **Connects to**: Your Flowfull backend for all API calls
2. **⚡ Flowfull - Your Custom Backend** (Your Code)
* **Technology**: Node.js using flowfull-node (official starter kit)
* **Purpose**: Your business logic, data management, custom APIs
* **What you build**: Products API, orders, posts, custom features
* **Connects to**: Flowless for session validation via Bridge API
3. **🔐 Flowless - Authentication Backend** (Managed by Pubflow)
* Handles all authentication
* Manages user sessions
* Provides trust tokens
* Fully managed and scaled by Pubflow
4. **Pubflow Dashboard** (Managed by Pubflow)
* Configure your Flowless instance
* Monitor usage and analytics
* View logs and alerts
* Manage settings
***
## Request Flow
### Authentication Flow
```mermaid
sequenceDiagram
participant U as 👤 User
participant F as 🌐 Frontend
participant FL as 🔐 Flowless
U->>F: 1️⃣ Enter credentials (email, password)
F->>FL: 2️⃣ POST /auth/login {email, password}
FL->>FL: 3️⃣ Validate credentials (Argon2 hash check)
FL->>FL: 4️⃣ Create session (SHA-256 hash)
FL-->>F: 5️⃣ session_id + user data {id, email, name, ...}
F->>F: 6️⃣ Store session_id (localStorage/AsyncStorage)
F-->>U: ✅ Logged in successfully!
Note over F,FL: Session valid for 30 days (default)
```
### Two-Factor (2FA) Module Flow
If the [Two-Factor Authentication module](/modules/two-factor) is enabled for the instance, the Flowless server intercepts standard logins:
```mermaid
sequenceDiagram
participant U as 👤 User
participant F as 🌐 Frontend
participant FL as 🔐 Flowless
U->>F: 1️⃣ Enter credentials
F->>FL: 2️⃣ POST /auth/login
FL->>FL: 3️⃣ Check if 2FA required (active method)
FL->>FL: 4️⃣ Generate 6-digit code
FL-->>F: 5️⃣ Return Partial Session {requires_2fa: true, session_id}
Note over F,FL: Session status is "pending" (5 min expiry)
F->>U: 6️⃣ Prompt for code
U->>F: 7️⃣ Enter 6-digit code
F->>FL: 8️⃣ POST /auth/two_factor/verify {code, method: "email", action: "login"}
FL->>FL: 9️⃣ Validate code (Argon2 hash)
FL->>FL: 🔟 Promote Session (status="active", two_factor_verified=1)
FL-->>F: ✅ Logged in successfully!
```
### API Request Flow (with Bridge Validation)
```mermaid
sequenceDiagram
participant F as 🌐 Frontend
participant FF as ⚡ Flowfull (Your Backend)
participant C as 💾 Cache (Redis/LRU)
participant FL as 🔐 Flowless
F->>FF: 1️⃣ GET /api/items X-Session-ID: ses_xxx
FF->>C: 2️⃣ Check trust token cache (key: ses_xxx)
alt ✅ Cache Hit (97% of requests)
C-->>FF: 3️⃣ Trust token (valid) + user data
Note over FF,C: < 10ms response time
else ❌ Cache Miss (3% of requests)
FF->>FL: 4️⃣ POST /bridge/validate {session_id, bridge_secret}
FL->>FL: 5️⃣ Validate session (check expiry, IP, device)
FL-->>FF: 6️⃣ Trust token + user data (PASETO token)
FF->>C: 7️⃣ Cache trust token (TTL: 5 minutes)
Note over FF,FL: < 50ms response time
end
FF->>FF: 8️⃣ Validate trust token (verify signature)
FF->>FF: 9️⃣ Check permissions (role-based access)
FF->>FF: 🔟 Fetch items (database query)
FF-->>F: ✅ Items data {items: [...]}
Note over F,FL: Total: < 100ms (p95)
```
***
## Database Schema
Flowless uses a multi-database architecture supporting PostgreSQL, MySQL, LibSQL, and SQLite.
### Core Tables
#### users
```sql
CREATE TABLE users (
id VARCHAR(255) PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
username VARCHAR(255) UNIQUE,
password_hash VARCHAR(255),
name VARCHAR(255),
last_name VARCHAR(255),
phone VARCHAR(50),
picture TEXT,
is_verified BOOLEAN DEFAULT FALSE,
is_banned BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```
#### sessions
```sql
CREATE TABLE sessions (
id VARCHAR(255) PRIMARY KEY,
user_id VARCHAR(255) NOT NULL,
session_hash VARCHAR(255) UNIQUE NOT NULL,
ip_address VARCHAR(45),
user_agent TEXT,
device_id VARCHAR(255),
expires_at TIMESTAMP NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
```
#### social\_accounts
```sql
CREATE TABLE social_accounts (
id VARCHAR(255) PRIMARY KEY,
user_id VARCHAR(255) NOT NULL,
provider VARCHAR(50) NOT NULL,
provider_user_id VARCHAR(255) NOT NULL,
access_token TEXT,
refresh_token TEXT,
expires_at TIMESTAMP,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
UNIQUE(provider, provider_user_id)
);
```
#### tokens
```sql
CREATE TABLE tokens (
id VARCHAR(255) PRIMARY KEY,
user_id VARCHAR(255) NOT NULL,
token_hash VARCHAR(255) UNIQUE NOT NULL,
name VARCHAR(255),
expires_at TIMESTAMP,
last_used_at TIMESTAMP,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
```
### Module Hub Mutations
Flowless instances only initialize the **Core Tables** above. When optional capabilities are activated through the `Module Hub`, specific database migrations occur in the background.
#### Two-Factor Activation (`modules/two-factor`)
If the **Two-Factor (2FA)** module is triggered, the Hub executes `base.sql` and `ext-session.sql` scripts simultaneously:
1. **`two_factor` Table Initialization (`base.sql`)**
```sql
CREATE TABLE IF NOT EXISTS two_factor (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
method TEXT NOT NULL, -- 'email', 'sms', 'otp', 'passkeys'
code TEXT, -- Hashed code (Argon2id)
status TEXT NOT NULL DEFAULT 'active',
metadata TEXT, -- JSON
token_prefix TEXT,
created_at TEXT,
updated_at TEXT,
last_used_at TEXT NULL,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
UNIQUE (user_id, method)
);
```
2. **`sessions` Extension (`ext-session.sql`)**
```sql
ALTER TABLE sessions ADD COLUMN IF NOT EXISTS two_factor_verified INTEGER NOT NULL DEFAULT 0;
ALTER TABLE sessions ADD COLUMN IF NOT EXISTS two_factor_verified_at TEXT NULL;
ALTER TABLE sessions ADD COLUMN IF NOT EXISTS two_factor_methods TEXT NULL;
```
If disabled later, these rows remain dormant but the API routes cease checking them, ensuring backward compatibility.
#### Onboarding Activation (`modules/onboarding`)
Optional ALTER TABLE on `users` (no new tables):
* **core** — acquisition\_\* / team\_size\_range
* **ext-business** — is\_business, biz\_name, biz\_country, biz\_state, biz\_position, biz\_postal\_code
* **ext-privacy** — gdpr\_*, ccpa\_*, privacy\_region
API surface: `/auth/user/me/onboarding/complete`, `/auth/user/me` (PUT biz — see Business), `/auth/user/me/privacy*` (Privacy). Admin: `/auth/admin/analytics/acquisition*`, list filters on `GET /auth/users`, `PATCH /auth/admin/users/:id/privacy`. Docs: [Onboarding](/modules/onboarding), [Business](/modules/business), [Privacy](/modules/privacy), [Admin API](/api/admin).
***
## Security Architecture
### Multi-Layer Security
```mermaid
graph LR
A["📱 Client Request"] --> B["🚦 Rate Limiting (IP-based)"]
B --> C["✅ Input Validation (Zod schemas)"]
C --> D["🔐 Authentication (Argon2 hash)"]
D --> E["🎫 Session Validation (SHA-256 + expiry)"]
E --> F["🛡️ Authorization (Trust tokens)"]
F --> G["⚡ Business Logic (Your code)"]
G --> H["📤 Response (JSON)"]
style A fill:#9E9E9E,stroke:#616161,stroke-width:2px,color:#fff
style B fill:#F44336,stroke:#C62828,stroke-width:3px,color:#fff
style C fill:#FF9800,stroke:#E65100,stroke-width:3px,color:#fff
style D fill:#FFC107,stroke:#F57C00,stroke-width:3px,color:#fff
style E fill:#8BC34A,stroke:#558B2F,stroke-width:3px,color:#fff
style F fill:#03A9F4,stroke:#0277BD,stroke-width:3px,color:#fff
style G fill:#9C27B0,stroke:#6A1B9A,stroke-width:3px,color:#fff
style H fill:#4CAF50,stroke:#2E7D32,stroke-width:3px,color:#fff
```
### Security Layers
1. **Rate Limiting**
* IP-based limits
* Endpoint-specific rules
* Redis-backed for distributed systems
* Automatic DDoS protection
2. **Input Validation**
* Email format validation (RFC 5322)
* Password strength requirements
* SQL injection prevention (parameterized queries)
* XSS prevention (HTML escaping)
3. **Authentication**
* Argon2id password hashing
* Secure session generation
* OAuth 2.0 for social login
* Token-based API access
4. **Session Validation**
* SHA-256 session hashing
* IP address validation (optional)
* Device fingerprinting (optional)
* User agent validation (optional)
5. **Authorization**
* Trust token validation (PASETO)
* Bridge secret authentication
* Role-based access (your backend)
***
## Caching Strategy
Flowless uses a multi-tier caching strategy for optimal performance:
### Cache Layers
```mermaid
graph LR
A["📥 Request"] --> B{"💾 L1: Memory Cache (LRU)"}
B -->|"✅ Hit (80%)"| C["⚡ Return Cached < 1ms"]
B -->|"❌ Miss (20%)"| D{"☁️ L2: Redis Cache"}
D -->|"✅ Hit (15%)"| E["📤 Update L1 + Return < 5ms"]
D -->|"❌ Miss (5%)"| F["🗄️ Database Query < 20ms"]
F --> G["💾 Update L2 + L1"]
G --> H["📤 Return Data"]
style A fill:#9E9E9E,stroke:#616161,stroke-width:2px,color:#fff
style B fill:#4CAF50,stroke:#2E7D32,stroke-width:3px,color:#fff
style C fill:#8BC34A,stroke:#558B2F,stroke-width:2px,color:#fff
style D fill:#2196F3,stroke:#1565C0,stroke-width:3px,color:#fff
style E fill:#03A9F4,stroke:#0277BD,stroke-width:2px,color:#fff
style F fill:#FF9800,stroke:#E65100,stroke-width:3px,color:#fff
style G fill:#FFC107,stroke:#F57C00,stroke-width:2px,color:#fff
style H fill:#4CAF50,stroke:#2E7D32,stroke-width:2px,color:#fff
```
### What Gets Cached
1. **Sessions** (5 minutes)
* Session validation results
* User data associated with session
* Reduces database load
2. **Trust Tokens** (5 minutes)
* Validated trust tokens
* User permissions
* Cached in your backend (Flowfull)
3. **User Profiles** (10 minutes)
* User data for frequent lookups
* Invalidated on profile updates
* **Manual invalidation**: `POST /auth/invalidate/me` (10 req/5min rate limit)
4. **Rate Limit Counters** (Real-time)
* Request counts per IP/user
* Sliding window algorithm
### Cache Management
**Automatic Updates**:
* Profile updates (`PUT /auth/user/me`) use SURGICAL strategy - updates specific fields
* Critical changes (email, user\_type) use ATOMIC strategy - full refresh with rollback
* Picture uploads update cache immediately
**Manual Invalidation**:
* Endpoint: `POST /auth/invalidate/me`
* Use case: When backend updates data directly
* Rate limit: 10 requests per 5 minutes
* Clears both UnifiedCache (LRU) and Ultra/Redis
**Cache Repopulation**:
* Automatic on next request after invalidation
* Bridge validate endpoint repopulates cache on miss
* Ensures consistency across distributed systems
***
## Scalability
### Horizontal Scaling
Flowless automatically scales horizontally:
```
┌─────────────────────────────────────┐
│ Load Balancer │
└─────────────────────────────────────┘
│ │ │
┌────▼───┐ ┌──▼────┐ ┌──▼────┐
│ Node 1 │ │ Node 2│ │ Node 3│
└────┬───┘ └───┬───┘ └───┬───┘
│ │ │
┌────▼─────────▼─────────▼────┐
│ Redis Cache Cluster │
└──────────────────────────────┘
│ │ │
┌────▼───┐ ┌──▼────┐ ┌──▼────┐
│ DB 1 │ │ DB 2 │ │ DB 3 │
│(Primary)│ │(Read) │ │(Read) │
└────────┘ └───────┘ └───────┘
```
### Performance Characteristics
| Metric | Value |
|--------|-------|
| **Latency** | < 50ms (p95) |
| **Throughput** | 10,000+ req/sec |
| **Availability** | 99.9% SLA |
| **Session Validation** | < 10ms (cached) |
| **Database Queries** | < 20ms (p95) |
***
## Next Steps
* [**Instance Setup**](/instance-setup/creating-instance) - Create your instance
* [**API Reference**](/api/authentication) - Explore the API
* [**Security Best Practices**](/security/best-practices) - Secure your integration
* [**Bridge Integration**](/guides/bridge-integration) - Connect your backend
---
---
url: /security/authentication.md
---
# Authentication Security
::: warning COMING SOON
This page is under construction. Check back soon for complete documentation.
:::
Deep dive into authentication security in Flowless.
## Overview
This page will cover:
* Password hashing (Argon2id)
* Brute force protection
* Account lockout
* Two-factor authentication
* Security headers
***
## Coming Soon
Comprehensive security guide covering:
* Password security
* Authentication attacks
* Protection mechanisms
* Security headers
* Best practices
***
## Next Steps
* [**Best Practices**](/security/best-practices) - Security best practices
* [**Session Security**](/security/sessions) - Session security
* [**Rate Limiting**](/security/rate-limiting) - Rate limiting
---
---
url: /api/blog.md
---
# Blog API
The Blog API covers the modular content system used for posts, categories, tags, comments, reactions, bookmarks, views, translations, and SEO support.
This page is written to help developers understand the moving parts quickly, not just memorize endpoints.
## How to read this page
Each route is documented like a normal operation page:
* what it does
* who can call it
* the relevant request shape
* a concrete response example
## Base path
All routes live under `/api/v1/posts`.
## What the API is for
* Reading and listing posts
* Creating and updating posts
* Managing categories and tags
* Handling comments and moderation
* Tracking reactions, bookmarks, views, and stats
* Supporting translations and SEO routes
## Languages
Blog routes answer only when `BLOG_ENABLED=true`. Otherwise they return `503 MODULE_DISABLED`. `BLOG_I18N_ENABLED=true` opens translation routes. A post still stores its language code when i18n is off. `GLOBAL_LANG` is the email and system-message language, not the blog language. See [Blog module](/modules/blog).
A post or category stores an [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) code, such as `es`. The display name is not stored.
If `lang` is omitted on create, the post or category uses the blog default language. A code outside this list is rejected.
On list endpoints, `lang` is one of these codes. An admin or moderator can pass `lang=all`, or omit `lang`, to list every language. A public request with no `lang`, or with `lang=all`, stays on the default language. An unknown code is rejected on create and falls back to the default language on list.
| Code | English name |
|------|----------------|
| `aa` | Afar |
| `ab` | Abkhazian |
| `ae` | Avestan |
| `af` | Afrikaans |
| `ak` | Akan |
| `am` | Amharic |
| `an` | Aragonese |
| `ar` | Arabic |
| `as` | Assamese |
| `av` | Avaric |
| `ay` | Aymara |
| `az` | Azerbaijani |
| `ba` | Bashkir |
| `be` | Belarusian |
| `bg` | Bulgarian |
| `bi` | Bislama |
| `bm` | Bambara |
| `bn` | Bengali |
| `bo` | Tibetan |
| `br` | Breton |
| `bs` | Bosnian |
| `ca` | Catalan |
| `ce` | Chechen |
| `ch` | Chamorro |
| `co` | Corsican |
| `cr` | Cree |
| `cs` | Czech |
| `cu` | Church Slavic |
| `cv` | Chuvash |
| `cy` | Welsh |
| `da` | Danish |
| `de` | German |
| `dv` | Divehi |
| `dz` | Dzongkha |
| `ee` | Ewe |
| `el` | Greek |
| `en` | English |
| `eo` | Esperanto |
| `es` | Spanish |
| `et` | Estonian |
| `eu` | Basque |
| `fa` | Persian |
| `ff` | Fulah |
| `fi` | Finnish |
| `fj` | Fijian |
| `fo` | Faroese |
| `fr` | French |
| `fy` | Western Frisian |
| `ga` | Irish |
| `gd` | Scottish Gaelic |
| `gl` | Galician |
| `gn` | Guarani |
| `gu` | Gujarati |
| `gv` | Manx |
| `ha` | Hausa |
| `he` | Hebrew |
| `hi` | Hindi |
| `ho` | Hiri Motu |
| `hr` | Croatian |
| `ht` | Haitian |
| `hu` | Hungarian |
| `hy` | Armenian |
| `hz` | Herero |
| `ia` | Interlingua |
| `id` | Indonesian |
| `ie` | Interlingue |
| `ig` | Igbo |
| `ii` | Sichuan Yi |
| `ik` | Inupiaq |
| `io` | Ido |
| `is` | Icelandic |
| `it` | Italian |
| `iu` | Inuktitut |
| `ja` | Japanese |
| `jv` | Javanese |
| `ka` | Georgian |
| `kg` | Kongo |
| `ki` | Kikuyu |
| `kj` | Kuanyama |
| `kk` | Kazakh |
| `kl` | Kalaallisut |
| `km` | Khmer |
| `kn` | Kannada |
| `ko` | Korean |
| `kr` | Kanuri |
| `ks` | Kashmiri |
| `ku` | Kurdish |
| `kv` | Komi |
| `kw` | Cornish |
| `ky` | Kyrgyz |
| `la` | Latin |
| `lb` | Luxembourgish |
| `lg` | Ganda |
| `li` | Limburgan |
| `ln` | Lingala |
| `lo` | Lao |
| `lt` | Lithuanian |
| `lu` | Luba-Katanga |
| `lv` | Latvian |
| `mg` | Malagasy |
| `mh` | Marshallese |
| `mi` | Maori |
| `mk` | Macedonian |
| `ml` | Malayalam |
| `mn` | Mongolian |
| `mr` | Marathi |
| `ms` | Malay |
| `mt` | Maltese |
| `my` | Burmese |
| `na` | Nauru |
| `nb` | Norwegian Bokmål |
| `nd` | North Ndebele |
| `ne` | Nepali |
| `ng` | Ndonga |
| `nl` | Dutch |
| `nn` | Norwegian Nynorsk |
| `no` | Norwegian |
| `nr` | South Ndebele |
| `nv` | Navajo |
| `ny` | Chichewa |
| `oc` | Occitan |
| `oj` | Ojibwa |
| `om` | Oromo |
| `or` | Odia |
| `os` | Ossetian |
| `pa` | Punjabi |
| `pi` | Pali |
| `pl` | Polish |
| `ps` | Pashto |
| `pt` | Portuguese |
| `qu` | Quechua |
| `rm` | Romansh |
| `rn` | Rundi |
| `ro` | Romanian |
| `ru` | Russian |
| `rw` | Kinyarwanda |
| `sa` | Sanskrit |
| `sc` | Sardinian |
| `sd` | Sindhi |
| `se` | Northern Sami |
| `sg` | Sango |
| `si` | Sinhala |
| `sk` | Slovak |
| `sl` | Slovenian |
| `sm` | Samoan |
| `sn` | Shona |
| `so` | Somali |
| `sq` | Albanian |
| `sr` | Serbian |
| `ss` | Swati |
| `st` | Southern Sotho |
| `su` | Sundanese |
| `sv` | Swedish |
| `sw` | Swahili |
| `ta` | Tamil |
| `te` | Telugu |
| `tg` | Tajik |
| `th` | Thai |
| `ti` | Tigrinya |
| `tk` | Turkmen |
| `tl` | Tagalog |
| `tn` | Tswana |
| `to` | Tongan |
| `tr` | Turkish |
| `ts` | Tsonga |
| `tt` | Tatar |
| `tw` | Twi |
| `ty` | Tahitian |
| `ug` | Uyghur |
| `uk` | Ukrainian |
| `ur` | Urdu |
| `uz` | Uzbek |
| `ve` | Venda |
| `vi` | Vietnamese |
| `vo` | Volapük |
| `wa` | Walloon |
| `wo` | Wolof |
| `xh` | Xhosa |
| `yi` | Yiddish |
| `yo` | Yoruba |
| `za` | Zhuang |
| `zh` | Chinese |
| `zu` | Zulu |
## Rate limits
Three buckets. The window is `BLOG_RATE_LIMIT_WINDOW` (default `3600` seconds). The same window is `rate.window` on `BLOG_MCU`. The counter key is the user id when a session is present, otherwise the client IP. Over the limit the route returns `429` with `code: RATE_LIMIT_EXCEEDED`.
| Bucket | Default | Env | MCU | Who is counted |
|--------|---------|-----|-----|----------------|
| `post` | 10 | `BLOG_POST_RATE_LIMIT` | `rate.post` | Everyone except a session that can publish |
| `comment` | 30 | `BLOG_COMMENT_RATE_LIMIT` | `rate.comment` | Every caller, including publishers |
| `view` | 200 | `BLOG_VIEW_RATE_LIMIT` | `rate.view` | Every caller, including publishers |
A session can publish when its role is in `BLOG_ALLOWED_POST_ROLES` or `BLOG_ADMIN_ROLES`. The defaults are `admin`, `superadmin`, `author`, and `editor`. Those sessions skip the `post` bucket. They still count toward `comment` and `view`.
`post` bucket:
* `GET /api/v1/posts/authors/:id`
* `POST /api/v1/posts`
* `PUT /api/v1/posts/:id`
* `DELETE /api/v1/posts/:id`
* `POST /api/v1/posts/:id/publish`
* `POST /api/v1/posts/:id/unpublish`
* `POST /api/v1/posts/:id/schedule`
* `POST /api/v1/posts/:id/restore`
* `POST /api/v1/posts/:id/featured-image`
* `DELETE /api/v1/posts/:id/featured-image`
* `POST /api/v1/posts/categories`
* `POST /api/v1/posts/categories/bulk`
* `PUT /api/v1/posts/categories/:id`
* `DELETE /api/v1/posts/categories/:id`
* `POST /api/v1/posts/tags`
* `POST /api/v1/posts/tags/bulk`
* `PUT /api/v1/posts/tags/:id`
* `DELETE /api/v1/posts/tags/:id`
* `POST /api/v1/posts/:id/bookmark`
* `DELETE /api/v1/posts/:id/bookmark`
* `POST /api/v1/posts/id/:id/translations`
* `PUT /api/v1/posts/id/:id/translations/:lang`
* `DELETE /api/v1/posts/id/:id/translations/:lang`
`comment` bucket:
* `POST /api/v1/posts/:id/comments`
* `PUT /api/v1/posts/:id/comments/:commentId`
* `DELETE /api/v1/posts/:id/comments/:commentId`
* `POST /api/v1/posts/comments/:commentId/moderate`
* `POST /api/v1/posts/:id/reactions`
`view` bucket:
* `POST /api/v1/posts/:id/view`
List and read routes other than the author profile are not in these buckets.
## Route map
| Method | Path | Auth | Purpose |
|--------|------|------|---------|
| `GET` | `/api/v1/posts` | Optional | List posts with filters and pagination |
| `GET` | `/api/v1/posts/authors/:id` | Public | Get author profile |
| `GET` | `/api/v1/posts/:slug` | Optional | Read one post by slug |
| `GET` | `/api/v1/posts/id/:id` | Optional | Read one post by id |
| `POST` | `/api/v1/posts` | Session + writer role | Create a post |
| `PUT` | `/api/v1/posts/:id` | Session + owner/admin | Update a post |
| `DELETE` | `/api/v1/posts/:id` | Session + owner/admin | Delete a post |
| `POST` | `/api/v1/posts/:id/publish` | Session + owner/admin | Publish a draft |
| `POST` | `/api/v1/posts/:id/unpublish` | Session + owner/admin | Return a post to draft |
| `POST` | `/api/v1/posts/:id/schedule` | Session + owner/admin | Schedule a post |
| `POST` | `/api/v1/posts/:id/restore` | Session + admin | Restore a soft-deleted post |
| `POST` | `/api/v1/posts/:id/featured-image` | Session + owner/admin | Upload featured image |
| `DELETE` | `/api/v1/posts/:id/featured-image` | Session + owner/admin | Delete featured image |
| `GET` | `/api/v1/posts/categories` | Public | List categories |
| `POST` | `/api/v1/posts/categories` | Session + admin | Create a category |
| `PUT` | `/api/v1/posts/categories/:id` | Session + admin | Update a category |
| `DELETE` | `/api/v1/posts/categories/:id` | Session + admin | Delete a category |
| `GET` | `/api/v1/posts/tags` | Public | List tags |
| `POST` | `/api/v1/posts/tags` | Session + admin | Create a tag |
| `PUT` | `/api/v1/posts/tags/:id` | Session + admin | Update a tag |
| `DELETE` | `/api/v1/posts/tags/:id` | Session + admin | Delete a tag |
| `GET` | `/api/v1/posts/:id/comments` | Optional | List comments |
| `POST` | `/api/v1/posts/:id/comments` | Conditional | Create a comment |
| `GET` | `/api/v1/posts/:id/reactions` | Optional | Read reaction counts |
| `POST` | `/api/v1/posts/:id/reactions` | Session | Add or toggle a reaction |
| `POST` | `/api/v1/posts/:id/bookmark` | Session | Bookmark a post |
| `GET` | `/api/v1/posts/me/bookmarks` | Session | List bookmarks |
| `POST` | `/api/v1/posts/:id/view` | Public | Track a view |
| `GET` | `/api/v1/posts/:id/stats` | Optional | Read aggregated stats |
| `GET` | `/api/v1/posts/seo/sitemap.xml` | Public | Generate the sitemap |
## Route details
### Posts
#### `GET /api/v1/posts/authors/:id`
Get one public author profile by id.
Auth: public.
Rate limit: `post` bucket. See [Rate limits](#rate-limits).
#### `GET /api/v1/posts`
List posts with pagination and filters.
Auth: optional.
Returns: a paginated list of posts.
Query params:
* `page`
* `limit`
* `sort`
* `order`
* `status`
* `visibility`
* `category`
* `tag`
* `author`
* `q`
* `lang` — ISO 639-1 code. Admins may pass `all`. See [Languages](#languages).
Example response:
```json
{
"data": [],
"user_context": {
"authenticated": false
},
"meta": {
"page": 1,
"limit": 10,
"total": 0,
"hasMore": false
}
}
```
#### `GET /api/v1/posts/:slug`
Read one post by slug.
#### `GET /api/v1/posts/id/:id`
Read one post by id.
#### `POST /api/v1/posts`
Create a new post.
Auth: session + writer role.
Rate limit: `post` bucket. A session that can publish is not counted. See [Rate limits](#rate-limits).
Required body fields:
* `title`
* `slug`
* `body`
* `body_format`
* `visibility`
Optional body fields:
* `excerpt`
* `comments_enabled`
* `reactions_enabled`
* `scheduled_at`
* `lang` — ISO 639-1 code, for example `"lang": "es"`. Omitted means the default language. The same field can be sent on update.
#### `PUT /api/v1/posts/:id`
Update an existing post.
Auth: session + owner/admin.
Rate limit: `post` bucket. A session that can publish is not counted. See [Rate limits](#rate-limits).
#### `DELETE /api/v1/posts/:id`
Delete a post.
Auth: session + owner/admin.
Rate limit: `post` bucket. A session that can publish is not counted. See [Rate limits](#rate-limits).
#### `POST /api/v1/posts/:id/publish`
Publish a draft post.
Auth: session + owner/admin.
Rate limit: `post` bucket. A session that can publish is not counted. See [Rate limits](#rate-limits).
#### `POST /api/v1/posts/:id/unpublish`
Return a published post to draft.
Auth: session + owner/admin.
Rate limit: `post` bucket. A session that can publish is not counted. See [Rate limits](#rate-limits).
#### `POST /api/v1/posts/:id/schedule`
Schedule a post for later publishing.
Auth: session + owner/admin.
Rate limit: `post` bucket. A session that can publish is not counted. See [Rate limits](#rate-limits).
#### `POST /api/v1/posts/:id/restore`
Restore a previously soft-deleted post.
Auth: session + admin.
Rate limit: `post` bucket. A session that can publish is not counted. See [Rate limits](#rate-limits).
#### `POST /api/v1/posts/:id/featured-image`
Upload featured image using multipart form-data.
Auth: session + owner/admin.
Rate limit: `post` bucket. A session that can publish is not counted. See [Rate limits](#rate-limits).
#### `DELETE /api/v1/posts/:id/featured-image`
Delete the current featured image.
Auth: session + owner/admin.
Rate limit: `post` bucket. A session that can publish is not counted. See [Rate limits](#rate-limits).
### Categories and tags
#### `GET /api/v1/posts/categories`
List categories.
Auth: public.
#### `POST /api/v1/posts/categories`
Create a category.
Auth: session + admin.
Rate limit: `post` bucket, including `POST /api/v1/posts/categories/bulk`. A session that can publish is not counted. See [Rate limits](#rate-limits).
#### `PUT /api/v1/posts/categories/:id`
Update a category.
Auth: session + admin.
Rate limit: `post` bucket. A session that can publish is not counted. See [Rate limits](#rate-limits).
#### `DELETE /api/v1/posts/categories/:id`
Delete a category.
Auth: session + admin.
Rate limit: `post` bucket. A session that can publish is not counted. See [Rate limits](#rate-limits).
#### `GET /api/v1/posts/tags`
List tags. Optional `lang` is an ISO 639-1 code and returns only tags stored with that code. Omit `lang`, or pass `all`, to return every tag. Tags with no `lang` appear only in that full list.
Auth: public.
#### `POST /api/v1/posts/tags`
Create a tag. Optional `lang` is an ISO 639-1 code. When it is omitted, the tag is stored as `BLOG_DEFAULT_LANG`. The same field applies to `POST /api/v1/posts/tags/bulk`.
Auth: session + admin.
Rate limit: `post` bucket, including `POST /api/v1/posts/tags/bulk`. A session that can publish is not counted. See [Rate limits](#rate-limits).
#### `PUT /api/v1/posts/tags/:id`
Update a tag.
Auth: session + admin.
Rate limit: `post` bucket. A session that can publish is not counted. See [Rate limits](#rate-limits).
#### `DELETE /api/v1/posts/tags/:id`
Delete a tag.
Auth: session + admin.
Rate limit: `post` bucket. A session that can publish is not counted. See [Rate limits](#rate-limits).
### Comments
#### `GET /api/v1/posts/:id/comments`
List comments for a post.
Auth: optional.
#### `POST /api/v1/posts/:id/comments`
Create a comment.
Auth: conditional.
Rate limit: `comment` bucket. Every caller is counted. See [Rate limits](#rate-limits).
#### `PUT /api/v1/posts/:id/comments/:commentId`
Update a comment.
Auth: session.
Rate limit: `comment` bucket. Every caller is counted. See [Rate limits](#rate-limits).
#### `DELETE /api/v1/posts/:id/comments/:commentId`
Delete a comment.
Auth: session.
Rate limit: `comment` bucket. Every caller is counted. See [Rate limits](#rate-limits).
#### `POST /api/v1/posts/comments/:commentId/moderate`
Moderate a comment.
Auth: session + moderator/admin.
Rate limit: `comment` bucket. Every caller is counted. See [Rate limits](#rate-limits).
### Engagement
#### `GET /api/v1/posts/:id/reactions`
Read reaction counters for one post.
Auth: optional.
#### `POST /api/v1/posts/:id/reactions`
Add or toggle a reaction.
Auth: session.
Rate limit: `comment` bucket. Every caller is counted. See [Rate limits](#rate-limits).
#### `POST /api/v1/posts/:id/bookmark`
Bookmark a post.
Auth: session.
Rate limit: `post` bucket. A session that can publish is not counted. See [Rate limits](#rate-limits).
#### `DELETE /api/v1/posts/:id/bookmark`
Remove a bookmark.
Auth: session.
Rate limit: `post` bucket. A session that can publish is not counted. See [Rate limits](#rate-limits).
#### `GET /api/v1/posts/me/bookmarks`
List current user bookmarks.
Auth: session.
#### `POST /api/v1/posts/:id/view`
Track a view.
Auth: public.
Rate limit: `view` bucket. Every caller is counted. See [Rate limits](#rate-limits).
#### `GET /api/v1/posts/:id/stats`
Read aggregated stats.
Auth: optional.
### Translations and SEO
#### `GET /api/v1/posts/id/:id/translations`
List translations for a post.
Auth: optional.
#### `POST /api/v1/posts/id/:id/translations`
Create a translation.
Auth: session + writer role.
Rate limit: `post` bucket. A session that can publish is not counted. See [Rate limits](#rate-limits).
#### `PUT /api/v1/posts/id/:id/translations/:lang`
Update a translation.
Auth: session + owner/admin.
Rate limit: `post` bucket. A session that can publish is not counted. See [Rate limits](#rate-limits).
#### `DELETE /api/v1/posts/id/:id/translations/:lang`
Delete a translation.
Auth: session + owner/admin.
Rate limit: `post` bucket. A session that can publish is not counted. See [Rate limits](#rate-limits).
#### `GET /api/v1/posts/seo/sitemap.xml`
Generate the SEO sitemap.
Auth: public.
## Response shape
Most blog routes use a consistent envelope:
```json
{
"data": {},
"user_context": {
"authenticated": true
},
"meta": {}
}
```
### Why that matters
* `data` holds the useful payload.
* `user_context` explains how the response was interpreted for the current viewer.
* `meta` carries pagination and query information.
## Example: list posts
```http
GET /api/v1/posts?page=1&limit=10&sort=created_at&order=desc
```
Example response:
```json
{
"data": [
{
"id": "post_1",
"slug": "hello-world",
"title": "Hello World",
"body": "# Hello",
"status": "published",
"visibility": "public"
}
],
"user_context": {
"authenticated": false
},
"meta": {
"page": 1,
"limit": 10,
"total": 1,
"hasMore": false
}
}
```
## Example: create a post
```http
POST /api/v1/posts
Content-Type: application/json
{
"title": "Why modular docs matter",
"slug": "why-modular-docs-matter",
"body": "# Why modular docs matter",
"body_format": "markdown",
"visibility": "public",
"comments_enabled": true
}
```
Example response:
```json
{
"data": {
"id": "post_2",
"slug": "why-modular-docs-matter",
"status": "draft"
},
"user_context": {
"authenticated": true,
"user_type": "writer"
},
"meta": {
"cached": false
}
}
```
## Typical flow
1. List posts publicly.
2. Create or edit a post as an authenticated writer.
3. Publish or schedule the post.
4. Allow comments and reactions if enabled.
5. Use stats and bookmarks for engagement.
## Practical notes
* The API is easiest to understand when you think in layers: content, moderation, engagement, and metadata.
* Use the response envelope to keep frontend code predictable.
* Treat publish and schedule as workflow actions, not just CRUD operations.
## Next
* [Modules overview](/modules/index)
* [Module Hub API](/api/module-hub)
* [Two-Factor Authentication API](/api/two-factor)
---
---
url: /modules/blog.md
---
# Blog Module
The Blog module adds a complete content layer on top of Flowless auth.
This page explains what is core, what is optional, and how to understand extensions without confusion.
## Core vs Extensions
| Area | Type | Required to use Blog? | Notes |
|------|------|------------------------|-------|
| Posts (CRUD + publish/unpublish/schedule) | Core | Yes | Main content workflow |
| Categories and tags | Core | Yes | Basic content organization |
| Comments | Core | No | Can be disabled per product policy |
| Reactions | Extension | No | Optional engagement layer |
| Bookmarks | Extension | No | Optional user utility feature |
| Views and stats | Extension | No | Optional analytics surface |
| Translations | Extension | No | Optional multilingual support. Language codes are listed in [Languages](/api/blog#languages). |
| Sitemap | Extension | No | Optional SEO automation |
| Featured image upload | Extension | No | Optional media enhancement |
## Friendly rule
Use Blog Core first, then enable extensions only when the product really needs them.
Extensions are not mandatory. For example, reactions can stay disabled and Blog still works correctly.
## Activation flow
1. Install Blog from Module Hub (usually via Pubflow Platform asset console).
2. Turn the routes on with `BLOG_ENABLED=true`. Until then every blog route returns `503 MODULE_DISABLED`. The server default is `false`.
3. Start with core routes (posts, categories, tags).
4. Enable optional extensions incrementally (comments, reactions, bookmarks, stats, translations, sitemap).
5. Keep runtime config and docs aligned.
`GLOBAL_LANG` is only the language of emails and system messages (`en`, `es`, `fr`). It does not enable the blog and it does not set a post's language.
| Variable | Default | What it does |
|----------|---------|----------------|
| `BLOG_ENABLED` | `false` | Opens the blog routes |
| `BLOG_I18N_ENABLED` | `false` | Opens translation create/update/delete. A post can still store `lang`, for example `"es"`, while this is off |
| `BLOG_DEFAULT_LANG` | `en` | Language used when create omits `lang` |
| `BLOG_MCU` | empty | One URI that overrides the separate `BLOG_*` flags when it is valid. Example: `blog://enabled@config/v1?i18n.enabled=true&i18n.default_lang=en` |
Post Types is a second switch. The blog works without it. See [Post Types](/modules/post-types). Installing that schema does not enable `/api/v1/post-types`; set `POST_TYPES_ENABLED=true` (or `POST_TYPES_MCU=post-types://enabled`) after the blog is on.
## Read the API docs
* [Blog operations](/operations/modules/blog)
* [Blog rate limits](/api/blog#rate-limits)
* [Module Hub operations](/operations/modules/module-hub)
* [Post Types module](/modules/post-types)
* [2FA module](/modules/two-factor)
---
---
url: /operations/modules/blog.md
---
# Blog Operations
Individual operation pages for the Blog module live under `operations/` and are grouped here for easy navigation.
## Posts
* [List Blog Posts](/operations/blogListPosts)
* [Get Blog Author Profile](/operations/blogGetAuthorProfile)
* [Get Blog Post by Slug](/operations/blogGetPostBySlug)
* [Get Blog Post by Id](/operations/blogGetPostById)
* [Create Blog Post](/operations/blogCreatePost)
* [Update Blog Post](/operations/blogUpdatePost)
* [Delete Blog Post](/operations/blogDeletePost)
* [Publish Blog Post](/operations/blogPublishPost)
* [Unpublish Blog Post](/operations/blogUnpublishPost)
* [Schedule Blog Post](/operations/blogSchedulePost)
* [Restore Blog Post](/operations/blogRestorePost)
## Media
* [Upload Blog Featured Image](/operations/blogUploadFeaturedImage)
* [Delete Blog Featured Image](/operations/blogDeleteFeaturedImage)
## Categories and Tags
* [List Blog Categories](/operations/blogListCategories)
* [Create Blog Category](/operations/blogCreateCategory)
* [Create Blog Categories in Bulk](/operations/blogCreateCategoryBulk)
* [Update Blog Category](/operations/blogUpdateCategory)
* [Delete Blog Category](/operations/blogDeleteCategory)
* [List Blog Tags](/operations/blogListTags)
* [Create Blog Tag](/operations/blogCreateTag)
* [Create Blog Tags in Bulk](/operations/blogCreateTagBulk)
* [Update Blog Tag](/operations/blogUpdateTag)
* [Delete Blog Tag](/operations/blogDeleteTag)
## Comments
* [List Blog Comments](/operations/blogListComments)
* [Create Blog Comment](/operations/blogCreateComment)
* [Update Blog Comment](/operations/blogUpdateComment)
* [Delete Blog Comment](/operations/blogDeleteComment)
* [Moderate Blog Comment](/operations/blogModerateComment)
## Engagement
* [Get Blog Reactions](/operations/blogGetReactions)
* [Add Blog Reaction](/operations/blogAddReaction)
* [Bookmark Blog Post](/operations/blogBookmarkPost)
* [Remove Blog Bookmark](/operations/blogRemoveBookmark)
* [List Blog Bookmarks](/operations/blogListBookmarks)
* [Track Blog View](/operations/blogTrackView)
* [Blog Stats](/operations/blogGetStats)
## Translations
* [List Blog Translations](/operations/blogListTranslations)
* [Create Blog Translation](/operations/blogCreateTranslation)
* [Update Blog Translation](/operations/blogUpdateTranslation)
* [Delete Blog Translation](/operations/blogDeleteTranslation)
## SEO
* [Blog Sitemap](/operations/blogSitemap)
---
---
url: /operations/blogAddReaction.md
---
Add or toggle a reaction on a blog post.
Auth: session.
## Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| `id` | path | string | Yes | Post id |
## Request Body
```json
{
"type": "like"
}
```
## Response 200
```json
{
"data": { "post_id": "post_2", "reaction": "like", "active": true },
"user_context": { "authenticated": true },
"meta": {}
}
```
## Response Errors
* `400` invalid reaction type
* `401` missing session
* `404` post not found
* `429` `RATE_LIMIT_EXCEEDED`
## Notes
* Rate limit: `comment` bucket, 30 requests / 3600s by default. Every caller is counted, including publishers. Over the limit returns `429` `RATE_LIMIT_EXCEEDED`. See [Rate limits](/api/blog#rate-limits).
* Use this for likes, hearts, or similar engagement reactions.
* The backend should keep the reaction model consistent per user.
---
---
url: /operations/blogSitemap.md
---
Generate the blog SEO sitemap.
Auth: public.
## Parameters
None.
## Request Body
None.
## Response 200
```xml
https://your-site.com/blog/hello-world
```
## Response Errors
* `500` sitemap generation error
## Notes
* Useful for search engine indexing.
* Keep it wired to the currently published content only.
---
---
url: /operations/blogGetStats.md
---
Read aggregated stats for a blog post.
Auth: optional.
## Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| `id` | path | string | Yes | Post id |
## Request Body
None.
## Response 200
```json
{
"data": {
"post_id": "post_2",
"views": 120,
"comments": 8,
"reactions": 15
},
"user_context": { "authenticated": false },
"meta": {}
}
```
## Response Errors
* `404` post not found
## Notes
* Good for dashboards and admin analytics.
* Can be cached if the backend exposes stale-friendly stats.
---
---
url: /operations/blogBookmarkPost.md
---
Bookmark a blog post.
Auth: session.
## Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| `id` | path | string | Yes | Post id |
## Request Body
Optional.
```json
{}
```
## Response 200
```json
{
"data": { "post_id": "post_2", "bookmarked": true },
"user_context": { "authenticated": true },
"meta": {}
}
```
## Response Errors
* `401` missing session
* `404` post not found
* `429` `RATE_LIMIT_EXCEEDED`
## Notes
* Rate limit: `post` bucket, 10 requests / 3600s by default. A session that can publish (`admin`, `superadmin`, `author`, `editor`, or the roles in `BLOG_ALLOWED_POST_ROLES` and `BLOG_ADMIN_ROLES`) is not counted. Otherwise `429` `RATE_LIMIT_EXCEEDED`. See [Rate limits](/api/blog#rate-limits).
* Use this for saved or favorite content flows.
* Works well with user dashboards and reading lists.
---
---
url: /guides/bridge-integration.md
---
# Bridge Integration Guide
Learn how to integrate Flowless with your custom backend (Flowfull) using the Bridge API for secure session validation.
***
## Overview
The **Bridge API** is the secure communication layer between your backend (Flowfull) and Flowless. It allows your backend to validate user sessions and receive trust tokens containing user information.
```mermaid
sequenceDiagram
participant Frontend
participant Flowfull
participant Flowless
Frontend->>Flowless: 1. Login
Flowless-->>Frontend: 2. session_id
Frontend->>Flowfull: 3. API request + session_id
Flowfull->>Flowless: 4. Validate session (Bridge)
Flowless-->>Flowfull: 5. Trust token + user data
Flowfull-->>Frontend: 6. Protected resource
```
***
## Prerequisites
Before integrating the Bridge API:
1. ✅ Created a Flowless instance
2. ✅ Have your Bridge Secret from the Pubflow dashboard
3. ✅ Have a backend application (Flowfull)
4. ✅ Understand basic authentication concepts
***
## Step 1: Configure Environment Variables
Add these to your backend's `.env` file:
```bash
# Flowless instance URL
FLOWLESS_URL=https://your-instance-name.pubflow.com
# Bridge Secret (KEEP SECURE!)
BRIDGE_SECRET=bridge_secret_abc123xyz789
# Validation mode (STANDARD, ADVANCED, STRICT)
VALIDATION_MODE=STANDARD
# Cache TTL for trust tokens (seconds)
TRUST_TOKEN_CACHE_TTL=300
```
::: danger
**Never commit your Bridge Secret to version control!**
* Store it in environment variables
* Use different secrets for dev/staging/prod
* Rotate it regularly
:::
***
## Step 2: Create Bridge Validation Function
### TypeScript/Node.js Example
```typescript
import { LRUCache } from 'lru-cache';
// Cache for trust tokens (5 minutes TTL)
const trustTokenCache = new LRUCache({
max: 10000,
ttl: 1000 * 60 * 5, // 5 minutes
});
interface ValidateSessionOptions {
sessionId: string;
ipAddress: string;
userAgent?: string;
deviceId?: string;
}
interface UserData {
id: string;
email: string;
name: string;
last_name?: string;
username?: string;
is_verified: boolean;
}
async function validateSession(options: ValidateSessionOptions): Promise {
const { sessionId, ipAddress, userAgent, deviceId } = options;
// Check cache first
const cachedToken = trustTokenCache.get(sessionId);
if (cachedToken) {
// Validate and decode cached token
const userData = await validateTrustToken(cachedToken);
if (userData) {
return userData;
}
}
// Call Flowless Bridge API
const response = await fetch(`${process.env.FLOWLESS_URL}/bridge/validate`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Bridge-Secret': process.env.BRIDGE_SECRET!,
},
body: JSON.stringify({
session_id: sessionId,
ip_address: ipAddress,
user_agent: userAgent,
device_id: deviceId,
}),
});
if (!response.ok) {
throw new Error('Session validation failed');
}
const data = await response.json();
if (!data.success || !data.data.valid) {
throw new Error('Invalid session');
}
// Cache the trust token
trustTokenCache.set(sessionId, data.data.trust_token);
return data.data.user;
}
async function validateTrustToken(token: string): Promise {
// Implement PASETO token validation here
// For now, we'll rely on the cache TTL
// In production, validate the token signature
try {
// Decode and validate PASETO token
// Return user data if valid
return null; // Placeholder
} catch (error) {
return null;
}
}
```
***
## Step 3: Create Authentication Middleware
### Express.js Example
```typescript
import { Request, Response, NextFunction } from 'express';
// Extend Express Request type
declare global {
namespace Express {
interface Request {
user?: UserData;
sessionId?: string;
}
}
}
async function authMiddleware(req: Request, res: Response, next: NextFunction) {
try {
// Get session ID from header
const sessionId = req.headers['x-session-id'] as string;
if (!sessionId) {
return res.status(401).json({
success: false,
error: 'No session ID provided',
});
}
// Get client info
const ipAddress = (req.headers['x-forwarded-for'] as string) || req.ip || '';
const userAgent = req.headers['user-agent'];
const deviceId = req.headers['x-device-id'] as string;
// Validate session with Flowless
const user = await validateSession({
sessionId,
ipAddress,
userAgent,
deviceId,
});
// Attach user to request
req.user = user;
req.sessionId = sessionId;
next();
} catch (error) {
return res.status(401).json({
success: false,
error: 'Invalid or expired session',
});
}
}
export { authMiddleware };
```
***
## Step 4: Use Middleware in Routes
```typescript
import express from 'express';
import { authMiddleware } from './middleware/auth';
const app = express();
// Public routes (no auth required)
app.get('/api/public/health', (req, res) => {
res.json({ success: true, status: 'healthy' });
});
// Protected routes (auth required)
app.get('/api/profile', authMiddleware, (req, res) => {
res.json({
success: true,
data: req.user,
});
});
app.get('/api/items', authMiddleware, async (req, res) => {
// req.user is available here
const items = await getItemsForUser(req.user!.id);
res.json({
success: true,
data: items,
});
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
```
***
## Step 5: Handle Frontend Requests
### React Example
```typescript
// api.ts
const API_URL = import.meta.env.VITE_API_URL;
const FLOWLESS_URL = import.meta.env.VITE_FLOWLESS_URL;
// Login function
export async function login(email: string, password: string) {
const response = await fetch(`${FLOWLESS_URL}/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
});
const data = await response.json();
if (data.success) {
// Store session ID
localStorage.setItem('session_id', data.data.session.session_id);
return data.data.user;
}
throw new Error(data.error);
}
// API call with session
export async function getProfile() {
const sessionId = localStorage.getItem('session_id');
if (!sessionId) {
throw new Error('Not authenticated');
}
const response = await fetch(`${API_URL}/api/profile`, {
headers: {
'X-Session-ID': sessionId,
},
});
const data = await response.json();
if (!data.success) {
throw new Error(data.error);
}
return data.data;
}
```
***
## Validation Modes
Choose the validation mode based on your security requirements:
### STANDARD (Recommended)
```bash
VALIDATION_MODE=STANDARD
```
* ✅ Session ID validation
* ✅ IP address validation
* ⚡ Fast and secure for most applications
### ADVANCED
```bash
VALIDATION_MODE=ADVANCED
```
* ✅ Session ID validation
* ✅ IP address validation
* ✅ Device ID validation
* 🔒 Better security for mobile apps
### STRICT
```bash
VALIDATION_MODE=STRICT
```
* ✅ Session ID validation
* ✅ IP address validation
* ✅ Device ID validation
* ✅ User agent validation
* 🔐 Maximum security for sensitive applications
***
## Caching Strategy
### Why Cache Trust Tokens?
* **Performance**: Avoid calling Flowless for every request
* **Scalability**: Reduce load on Flowless
* **Cost**: Reduce API usage
### Flowless Hybrid Cache
Flowless uses a dual-layer hybrid cache:
1. **Ultra/Redis** - Distributed cache shared across instances
2. **UnifiedSessionCache** - Fast LRU local cache
When you call `/auth/bridge/validate`:
* First checks Ultra/Redis (distributed)
* Falls back to UnifiedCache (local)
* On cache miss: queries database and repopulates both caches
### Cache Invalidation
When your backend updates user data directly, you can invalidate the cache:
```typescript
// After updating user in your database
await db.updateTable('users')
.set({ name: 'New Name' })
.where('id', '=', userId)
.execute();
// Invalidate Flowless cache to force fresh data
await fetch(`${FLOWLESS_URL}/auth/invalidate/me`, {
method: 'POST',
headers: {
'X-Session-ID': sessionId,
},
});
// Next bridge/validate call will fetch fresh data from DB
```
**Rate Limit**: 10 requests per 5 minutes per user
### Your Backend Cache Implementation
For optimal performance, implement caching in your backend:
```typescript
import { LRUCache } from 'lru-cache';
const cache = new LRUCache({
max: 10000, // Max 10,000 tokens
ttl: 1000 * 60 * 5, // 5 minutes
});
// Cache hit rate tracking
let cacheHits = 0;
let cacheMisses = 0;
function getCacheHitRate() {
const total = cacheHits + cacheMisses;
return total > 0 ? (cacheHits / total) * 100 : 0;
}
```
***
## Error Handling
```typescript
try {
const user = await validateSession({ sessionId, ipAddress });
} catch (error) {
if (error.message === 'Invalid session') {
// Session expired or invalid
return res.status(401).json({ error: 'Please login again' });
}
if (error.message === 'IP address mismatch') {
// Possible session hijacking
return res.status(403).json({ error: 'Security violation detected' });
}
// Other errors
return res.status(500).json({ error: 'Internal server error' });
}
```
***
## Next Steps
* [**Sessions API**](/api/sessions) - Session management endpoints
* [**Security Best Practices**](/security/best-practices) - Secure your integration
* [**Testing Guide**](/guides/testing) - Test your integration
---
---
url: /api/bridge-validate.md
---
## About This Endpoint
The Bridge Validate endpoint is a critical component for integrating your backend with Flowless. It provides:
### Hybrid Cache Architecture
The endpoint uses a dual-layer caching system for optimal performance:
1. **Ultra/Redis (Distributed Cache)** - First priority, shared across instances
2. **UnifiedSessionCache (LRU)** - Fast local cache fallback
**Cache Flow:**
```
Request → Ultra/Redis Check → UnifiedCache Check → Database Query → Repopulate Both Caches
```
### Performance Benefits
* **Cache Hit (Ultra/Redis)**: ~5-10ms response time
* **Cache Hit (UnifiedCache)**: ~2-5ms response time
* **Cache Miss (Database)**: ~50-100ms, but automatically repopulates cache
* **Subsequent Requests**: Fast cache hits
### Cache Invalidation
When you need to force fresh data (e.g., after direct database updates), use the [**Cache Invalidation endpoint**](/api/cache-invalidate):
```http
POST /auth/invalidate/me
```
This clears both cache layers, ensuring the next validation request fetches fresh data from the database.
**Invalidation Flow:**
```
1. POST /auth/invalidate/me → Clears Ultra/Redis + UnifiedCache
2. POST /auth/bridge/validate → Cache MISS → Fetches from DB
3. System automatically repopulates both caches
4. Future requests → Cache HIT with fresh data
```
***
## Related Endpoints
* [**POST /auth/invalidate/me**](/api/cache-invalidate) - Invalidate user cache to force fresh data
* [**GET /auth/me**](/api/auth-me) - Get current user information
* [**POST /auth/login**](/api/auth-login) - User login (creates session)
---
---
url: /api/business.md
---
# Business API
Business profile fields on the authenticated user (`ext-business` of [Onboarding](/modules/onboarding)).
There is **no** separate `/auth/user/me/business*` route family. Writes go through the existing profile endpoints.
## Write / read
| Capability | Path |
|------------|------|
| Update business profile | `PUT /auth/user/me` (`is_business`, `biz_name`, `biz_country`, `biz_state`, `biz_position`, `biz_postal_code`) |
| Wizard upsert (first run) | `POST /auth/user/me/onboarding/complete` |
| Read profile (includes biz when installed) | `GET /auth/user/me` |
Requires Module Hub `onboarding` **ext-business** columns. Missing columns → biz fields ignored or omitted (same graceful behavior as other onboarding extensions).
`PUT /auth/user/me` **rejects** acquisition and privacy fields — use [complete](/api/onboarding) or [Privacy API](/api/privacy).
## Example
```http
PUT /auth/user/me
Content-Type: application/json
X-Session-ID:
{
"is_business": true,
"biz_name": "Acme Corp",
"biz_country": "US",
"biz_state": "California",
"biz_position": "CTO",
"biz_postal_code": "94107"
}
```
## Admin analytics
Admin acquisition analytics, list filters (`is_business` / `biz_country`), and related reporting: see [Admin API](/api/admin).
## Operations
* [Update user profile](/operations/updateUserProfile)
* [Complete onboarding](/operations/onboardingComplete)
* [Get current user](/operations/getCurrentUser)
* [Business operations index](/operations/modules/business)
* [Onboarding API](/api/onboarding)
* [Business module](/modules/business)
---
---
url: /modules/business.md
---
# Business Module
Business is an **extension** of the [Onboarding](/modules/onboarding) Module Hub package (`ext-business.sql`). It ALTERs `users` with a business profile (`is_business`, `biz_*`) — no new tables.
Install with onboarding `target: "all"` (or the business component after core).
## Ownership (Onboarding family)
| Concern | Write | Read |
|---------|-------|------|
| Business profile | `PUT /auth/user/me` or `POST .../onboarding/complete` | `GET /auth/user/me` |
| Acquisition / team size | complete only | never on GET |
| Privacy GDPR/CCPA | `/auth/user/me/privacy*` | GET me + GET privacy |
Business updates are **not** on the [Privacy](/modules/privacy) routes.
## Friendly rule
1. Install onboarding + ext-business via Module Hub.
2. First-run wizard may set biz fields via `POST /auth/user/me/onboarding/complete`.
3. After that, prefer `PUT /auth/user/me` for `is_business` / `biz_*` (incl. `biz_postal_code`).
4. Profile GET returns biz fields when columns exist.
## Columns (`ext-business.sql`)
| Column | Notes |
|--------|-------|
| `is_business` | Primary B2B flag |
| `biz_name` | Company / organization |
| `biz_country` | ISO alpha-2 |
| `biz_state` | State / province (free text) |
| `biz_position` | Role / title |
| `biz_postal_code` | Postal/ZIP or hyphenated range, max 32 |
## Admin analytics
| Method | Path | Notes |
|--------|------|-------|
| `GET` | `/auth/admin/analytics/acquisition` | Breakdown by channel/source |
| `GET` | `/auth/admin/analytics/acquisition/funnel` | Per-source verified/converted |
| `GET` | `/auth/users?is_business=&biz_country=&privacy_region=` | Admin list filters |
| `PATCH` | `/auth/admin/users/:id/privacy` | Admin privacy override |
See [Admin API](/api/admin) and [Onboarding operations](/operations/modules/onboarding).
## Docs
* [Business API](/api/business)
* [Business operations](/operations/modules/business)
* [Onboarding module](/modules/onboarding) (parent)
* [Complete onboarding](/operations/onboardingComplete)
* [Update user profile](/operations/updateUserProfile)
* [Module Hub dry-run](/operations/moduleHubModuleDryRun)
---
---
url: /operations/modules/business.md
---
# Business Operations
Business profile (`ext-business`) for the authenticated user — part of the [Onboarding](/modules/onboarding) module family.
No dedicated `/business*` HTTP family: use profile PUT / complete / GET.
## Profile write / read
* [Update user profile](/operations/updateUserProfile) — `PUT /auth/user/me` (preferred after first run; `is_business`, `biz_*` incl. `biz_postal_code`)
* [Complete onboarding](/operations/onboardingComplete) — `POST /auth/user/me/onboarding/complete` (wizard upsert)
* [Get current user](/operations/getCurrentUser) — `GET /auth/user/me` (returns biz when columns exist)
## Related Onboarding family
| Area | Ops index |
|------|-----------|
| Parent / complete / acquisition | [Onboarding operations](/operations/modules/onboarding) |
| GDPR / CCPA | [Privacy operations](/operations/modules/privacy) |
Business updates are **not** on privacy routes.
## Admin analytics
* [Acquisition analytics](/operations/adminAcquisitionAnalytics)
* [Acquisition funnel](/operations/adminAcquisitionFunnel)
* [List users](/operations/adminListUsers) — filters `is_business`, `biz_country`, `privacy_region`
* [Patch user privacy](/operations/adminPatchUserPrivacy)
## Related
* [Business API overview](/api/business)
* [Business module](/modules/business)
* [Onboarding operations](/operations/modules/onboarding)
* [Module Hub operations](/operations/modules/module-hub)
---
---
url: /api/cache-invalidate.md
---
# Cache Invalidation
Invalidate cached session data for efficient cache management in distributed systems.
***
## Overview
The cache invalidation endpoint allows authenticated users to clear their own cached session data. This is particularly useful when:
* Backend systems update user data directly in the database
* You need to ensure fresh data is loaded on the next request
* Profile changes made outside the standard flow need to be reflected immediately
* Multiple backend services share the same Flowless core
***
## Endpoint
```http
POST /auth/invalidate/me
```
**Authentication**: Required (Session-based)
**Rate Limit**: 10 requests per 5 minutes (per user)
***
## How It Works
### Cache Invalidation Flow
```mermaid
sequenceDiagram
participant Client
participant Backend
participant Flowless
participant Redis
participant Database
Client->>Flowless: POST /auth/invalidate/me
Note over Flowless: Check rate limit
Flowless->>Redis: Clear Ultra/Redis cache
Flowless->>Flowless: Clear UnifiedSessionCache
Flowless-->>Client: Success (cache cleared)
Note over Client,Database: Next request
Client->>Flowless: GET /auth/me (or bridge/validate)
Flowless->>Redis: Cache MISS
Flowless->>Database: Fetch fresh data
Database-->>Flowless: Latest user data
Flowless->>Redis: Repopulate cache
Flowless-->>Client: Fresh data returned
```
### Dual Cache Architecture
Flowless uses a hybrid caching system for maximum performance:
1. **UnifiedSessionCache (LRU)** - Fast in-memory local cache
2. **Ultra/Redis** - Distributed cache shared across instances
When you call `/auth/invalidate/me`, **both caches are cleared** simultaneously, ensuring:
* No stale data in any cache layer
* Next request fetches from database
* Automatic repopulation with fresh data
***
## Request
### Headers
```http
X-Session-ID: your-session-id-here
Content-Type: application/json
```
### Request Body
No request body required. The endpoint invalidates the cache for the authenticated user making the request.
***
## Response
### Success Response (200 OK)
```json
{
"success": true,
"message": "Cache invalidated successfully. Fresh data will be loaded on next request.",
"data": {
"invalidatedSessions": 2,
"executionTime": 15,
"strategy": "invalidate",
"nextRequestSource": "database"
},
"rateLimitInfo": {
"remaining": 9,
"resetTime": 1738483200000
}
}
```
**Response Fields**:
* `invalidatedSessions` - Number of cached sessions cleared (user may have multiple active sessions)
* `executionTime` - Time taken to invalidate cache (milliseconds)
* `strategy` - Cache update strategy used (always "invalidate" for this endpoint)
* `nextRequestSource` - Indicates next request will fetch from "database"
* `rateLimitInfo.remaining` - Remaining invalidation requests in current window
* `rateLimitInfo.resetTime` - Unix timestamp when rate limit resets
### Rate Limit Exceeded (429)
```json
{
"success": false,
"error": "Too many cache invalidation requests. Please try again later.",
"resetTime": 1738483200000,
"remaining": 0,
"code": "RATE_LIMIT_EXCEEDED"
}
```
### Unauthorized (401)
```json
{
"success": false,
"error": "Invalid or expired session"
}
```
***
## Rate Limiting
The cache invalidation endpoint uses intelligent rate limiting to prevent abuse:
| Limit Type | Value | Window | Identifier |
|------------|-------|--------|------------|
| Per User | 10 requests | 5 minutes | User ID |
**Why per-user limiting?**
* Self-service model - users manage their own cache
* Prevents individual user abuse
* Doesn't block other users
* Distributed tracking via Redis
**Why 10 requests per 5 minutes?**
* Balances legitimate use (profile updates, app synchronization) vs abuse
* More permissive than password reset (3/hour) - cache invalidation is less critical
* Less permissive than registration (10/min) - prevents spam
* Allows occasional bursts while preventing sustained abuse
***
## Use Cases
### 1. Backend Direct Updates
When your backend (Flowfull) updates user data directly:
```typescript
// Backend updates user profile directly in database
await db.updateTable('users')
.set({ name: 'New Name', picture: 'new-url.jpg' })
.where('id', '=', userId)
.execute();
// Notify user to invalidate cache on their next interaction
// OR call invalidate from backend using the user's session
await fetch(`${FLOWLESS_URL}/auth/invalidate/me`, {
method: 'POST',
headers: {
'X-Session-ID': userSessionId,
}
});
```
### 2. Multi-Backend Synchronization
When multiple backends share the same Flowless instance:
```typescript
// Backend A updates user
await backendA.updateUser(userId, { role: 'premium' });
// Backend B needs fresh data
// User calls invalidate/me, then next request to Backend B gets fresh data
```
### 3. Profile Import/Migration
When importing user data from external systems:
```typescript
// Import data from legacy system
await importUserData(userId, externalData);
// Clear cache so user sees updated data immediately
await invalidateUserCache(sessionId);
```
***
## Best Practices
### ✅ DO
* Call this endpoint **after** updating user data in your backend
* Use it for **occasional** cache refreshes when needed
* Implement proper error handling for rate limits
* Monitor rate limit headers to avoid hitting limits
### ❌ DON'T
* Call on **every** request (defeats the purpose of caching)
* Use as a substitute for proper cache update strategies
* Ignore rate limit errors (implement backoff)
* Call from frontend without user action (waste of resources)
***
## Example Integration
### Frontend Example (React)
```typescript
import { useState } from 'react';
function ProfileSync() {
const [syncing, setSyncing] = useState(false);
const [error, setError] = useState(null);
const handleSyncProfile = async () => {
setSyncing(true);
setError(null);
try {
const sessionId = localStorage.getItem('session_id');
// 1. Invalidate cache
const invalidateResponse = await fetch(
`${FLOWLESS_URL}/auth/invalidate/me`,
{
method: 'POST',
headers: {
'X-Session-ID': sessionId!,
},
}
);
const invalidateData = await invalidateResponse.json();
if (!invalidateData.success) {
throw new Error(invalidateData.error);
}
// 2. Fetch fresh profile data
const profileResponse = await fetch(`${FLOWLESS_URL}/auth/me`, {
headers: {
'X-Session-ID': sessionId!,
},
});
const profileData = await profileResponse.json();
if (profileData.success) {
console.log('Profile synced with fresh data:', profileData.data.user);
}
} catch (err: any) {
if (err.message.includes('rate limit')) {
setError('Too many sync requests. Please wait a few minutes.');
} else {
setError(err.message);
}
} finally {
setSyncing(false);
}
};
return (
{syncing ? 'Syncing...' : 'Sync Profile'}
{error &&
{error}
}
);
}
```
### Backend Example (Node.js/Hono)
```typescript
// After updating user data in your backend
async function updateUserAndInvalidateCache(
userId: string,
updates: Record,
sessionId: string
) {
// 1. Update user data in your database
await db.updateTable('users')
.set(updates)
.where('id', '=', userId)
.execute();
// 2. Invalidate Flowless cache
try {
await fetch(`${process.env.FLOWLESS_URL}/auth/invalidate/me`, {
method: 'POST',
headers: {
'X-Session-ID': sessionId,
},
});
console.log('Cache invalidated, next request will fetch fresh data');
} catch (error) {
console.warn('Cache invalidation failed (non-critical):', error);
// Don't fail the operation if cache invalidation fails
}
return { success: true };
}
```
***
## Performance Characteristics
| Metric | Value |
|--------|-------|
| Average Response Time | ~15-30ms |
| Cache Layers Cleared | 2 (UnifiedCache + Ultra/Redis) |
| Database Operations | 0 (no DB writes) |
| Sessions Affected | All active sessions for the user |
***
## Security Considerations
* ✅ **Authentication Required** - Only authenticated users can invalidate cache
* ✅ **Self-Service Only** - Users can only invalidate their own cache
* ✅ **Rate Limited** - 10 requests per 5 minutes prevents abuse
* ✅ **Audit Logging** - All invalidation attempts are logged
* ✅ **Distributed Tracking** - Rate limits tracked in Redis across instances
***
## Related Endpoints
* [**GET /auth/me**](/api/auth-me) - Get current user (will return fresh data after invalidation)
* [**POST /auth/bridge/validate**](/api/bridge-validate) - Bridge validation (repopulates cache on miss)
* [**PUT /auth/user/me**](/api/user-profile-update) - Update profile (auto-updates cache)
***
## FAQ
### When should I use this endpoint?
Use it when:
* Your backend updates user data directly in the database
* You need to force fresh data loading
* Multiple backends share the same Flowless instance
* You're debugging cache-related issues
### How often can I call this?
Up to 10 times per 5 minutes per user. If you need more frequent invalidation, consider:
* Using the standard update endpoints (they auto-update cache)
* Adjusting your architecture to use cache-aware updates
* Implementing a cache warming strategy
### What happens to other users?
Nothing. This endpoint only invalidates the cache for the **authenticated user** making the request. Other users' caches are unaffected.
### Does this log me out?
No. This only clears cached session data. Your session remains active. The next request will simply fetch fresh data from the database and repopulate the cache.
### What if I have multiple devices/sessions?
All cached sessions for your user ID are invalidated across **all devices**. The next request from any device will fetch fresh data.
***
## Next Steps
* [**Cache Architecture**](/architecture#caching) - Learn about the hybrid cache system
* [**Bridge Integration**](/guides/bridge-integration) - Integrate with your backend
* [**Session Management**](/guides/session-management) - Understand session lifecycle
---
---
url: /operations/cancelEmailChange.md
---
“This wasn’t me” on the current-inbox confirmation page. GET peeks. POST invalidates both halves that are still active; login email is unchanged. Not confirming already leaves the email unchanged.
---
---
url: /operations/postCcpaOptOut.md
---
Path: `POST /auth/user/me/privacy/ccpa-opt-out`\
Body: `{ "opt_out": boolean }`. Server sets `ccpa_opt_out_at` when true.
---
---
url: /api/password-change.md
---
---
---
url: /operations/changePassword.md
---
---
---
url: /operations/adminChangePassword.md
---
---
---
url: /operations/onboardingComplete.md
---
Finish first-run onboarding and optionally persist acquisition / business / privacy fields.
Path: `POST /auth/user/me/onboarding/complete`\
Auth: session. Rate limit: Ultra **10 / 10 minutes** per IP.
This route belongs to the **Onboarding module** family. Related components:
* [Business](/modules/business) / [Business operations](/operations/modules/business) — company profile (`ext-business`)
* [Privacy](/modules/privacy) / [Privacy operations](/operations/modules/privacy) — GDPR/CCPA (`ext-privacy`)
Acquisition fields are write-only (not returned on GET). Prefer [privacy routes](/api/privacy) for post-wizard GDPR/CCPA and [Business API](/api/business) / `PUT /auth/user/me` for later biz updates.
## Notes
* Idempotent / re-callable upsert.
* Missing module columns → still completes with `optional_fields_persisted: false`.
* Read biz/privacy via [Get current user](/operations/getCurrentUser) or [Get privacy](/operations/getUserPrivacy).
---
---
url: /operations/completePasswordReset.md
---
---
---
url: /operations/confirmEmailChange.md
---
GET peeks (email scanners do not apply the change). Each inbox has its own link to this route. POST consumes only that half. `users.email` is written when the other half is already confirmed. The first click returns a page asking to confirm the other inbox.
---
---
url: /core-concepts.md
---
# Core Concepts
Understanding these core concepts will help you make the most of Flowless and integrate it effectively into your application.
***
## Authentication vs. Authorization
### Authentication
**Authentication** is the process of verifying who a user is. Flowless handles this completely:
* User registration
* Login (email/password, social OAuth)
* Session creation and validation
* Password reset
* Email verification
### Authorization
**Authorization** is the process of determining what a user can do. This is handled by **your backend** (Flowfull):
* User roles and permissions
* Access control to resources
* Business logic rules
* Feature flags
**Key Point:** Flowless tells you WHO the user is. Your backend decides WHAT they can do.
***
## Sessions
### What is a Session?
A **session** represents an authenticated user's connection to your application. When a user logs in, Flowless creates a session and returns a `session_id`.
### Session Lifecycle
```mermaid
graph LR
A[User Logs In] --> B[Session Created]
B --> C[Session ID Returned]
C --> D[User Makes Requests]
D --> E{Session Valid?}
E -->|Yes| F[Request Processed]
E -->|No| G[401 Unauthorized]
F --> H{Session Expired?}
H -->|No| D
H -->|Yes| I[Refresh or Re-login]
```
### Session Properties
* **session\_id**: Unique identifier (e.g., `ses_abcdefghijk`)
* **user\_id**: Associated user
* **expires\_at**: Expiration timestamp (default: 7 days)
* **device\_id**: Optional device binding
* **ip\_address**: IP address (for validation)
* **user\_agent**: Browser/app identifier
### Session Security
Sessions are secured using:
* **SHA-256 hashing** - Session IDs are hashed before storage
* **Prefix system** - `ses_` for unhashed, `hashed_ses_` for hashed
* **Expiration** - Automatic cleanup of expired sessions
* **Device binding** - Optional device-specific sessions
* **IP validation** - Optional IP address validation
***
## Trust Tokens
### What are Trust Tokens?
**Trust tokens** are PASETO (Platform-Agnostic Security Tokens) that Flowless generates to securely communicate user information to your backend (Flowfull).
### How They Work
```mermaid
sequenceDiagram
participant Frontend
participant Flowfull
participant Flowless
Frontend->>Flowfull: API request + session_id
Flowfull->>Flowless: Validate session (Bridge API)
Flowless->>Flowless: Verify session
Flowless-->>Flowfull: Trust token + user data
Flowfull->>Flowfull: Validate trust token
Flowfull-->>Frontend: Protected resource
```
### Trust Token Contents
```json
{
"user_id": "usr_1234567890",
"session_id": "ses_abcdefghijk",
"email": "user@example.com",
"name": "John Doe",
"exp": 1733574000,
"iat": 1733570400
}
```
### Why Trust Tokens?
* **Security** - Cryptographically signed, cannot be forged
* **Performance** - Your backend can cache them
* **Stateless** - No need to query Flowless for every request
* **Tamper-proof** - Any modification invalidates the token
***
## Bridge Validation
### What is Bridge Validation?
**Bridge validation** is the process of your backend (Flowfull) validating a user's session with Flowless.
### Validation Modes
Flowless supports three validation modes:
#### 1. STANDARD (Default)
* Validates session ID
* Checks IP address
```typescript
// Environment variable
VALIDATION_MODE=STANDARD
```
#### 2. ADVANCED
* Validates session ID
* Checks IP address
* Validates device ID
```typescript
VALIDATION_MODE=ADVANCED
```
#### 3. STRICT
* Validates session ID
* Checks IP address
* Validates device ID
* Validates user agent
```typescript
VALIDATION_MODE=STRICT
```
### Bridge Secret
Your backend authenticates with Flowless using a **Bridge Secret**:
```bash
# In your Flowfull backend
BRIDGE_SECRET=your_secret_key_here
```
This secret is used to authenticate bridge validation requests.
***
## Rate Limiting
### What is Rate Limiting?
Rate limiting prevents abuse by limiting the number of requests a user or IP can make in a given time period.
### Default Limits
| Endpoint | Limit | Window |
|----------|-------|--------|
| `/auth/login` | 5 requests | 15 minutes |
| `/auth/register` | 3 requests | 1 hour |
| `/auth/password-reset` | 3 requests | 1 hour |
| `/auth/invalidate/me` | 10 requests | 5 minutes |
| API calls | 100 requests | 1 minute |
### Rate Limit Headers
Flowless returns rate limit information in response headers:
```
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1733570460
```
### Handling Rate Limits
```typescript
const response = await fetch('https://your-instance.pubflow.com/auth/login', {
method: 'POST',
// ...
});
if (response.status === 429) {
const resetTime = response.headers.get('X-RateLimit-Reset');
console.log(`Rate limited. Try again at ${new Date(resetTime * 1000)}`);
}
```
***
## Email Verification
### Why Email Verification?
Email verification ensures that:
* Users own the email address they registered with
* Reduces spam and fake accounts
* Enables password reset functionality
### Verification Flow
```mermaid
sequenceDiagram
participant User
participant App
participant Flowless
participant Email
User->>App: Register
App->>Flowless: POST /auth/register
Flowless->>Email: Send verification email
Flowless-->>App: User created (unverified)
Email->>User: Verification link
User->>Flowless: Click link
Flowless->>Flowless: Mark as verified
Flowless-->>User: Redirect to app
```
### Configuration
You can configure email verification in the Pubflow dashboard:
* **Required** - Users must verify before login
* **Optional** - Users can login without verification
* **Disabled** - No verification emails sent
***
## Password Security
### Password Requirements
Default requirements (configurable):
* Minimum 8 characters
* At least one uppercase letter
* At least one lowercase letter
* At least one number
* At least one special character
### Password Hashing
Flowless uses **Argon2id** for password hashing:
* Industry-standard algorithm
* Resistant to GPU attacks
* Automatic salt generation
* Configurable work factor
### Password Reset Flow
```mermaid
sequenceDiagram
participant User
participant App
participant Flowless
participant Email
User->>App: Request password reset
App->>Flowless: POST /user/request-password-reset
Flowless->>Email: Send reset email
Email->>User: Reset link
User->>App: Click link + enter new password
App->>Flowless: POST /user/reset-password
Flowless->>Flowless: Update password
Flowless-->>App: Success
```
***
## Social Authentication (OAuth)
### Supported Providers
Flowless supports OAuth 2.0 authentication with:
* Google
* Facebook
* GitHub
* Twitter
* LinkedIn
* Custom OAuth providers
### OAuth Flow
```mermaid
sequenceDiagram
participant User
participant App
participant Flowless
participant Provider
User->>App: Click "Login with Google"
App->>Flowless: GET /auth/social/google
Flowless-->>App: Redirect to Google
App->>Provider: User authorizes
Provider-->>Flowless: Callback with code
Flowless->>Provider: Exchange code for token
Provider-->>Flowless: Access token + user info
Flowless->>Flowless: Create/find user
Flowless-->>App: Redirect with session_id
```
### Account Linking
Users can link multiple social accounts to one Flowless account:
* Login with email/password, then link Google
* Login with Google, then link Facebook
* Unlink accounts at any time
***
## Next Steps
Now that you understand the core concepts:
* [**Architecture**](/architecture) - See how everything fits together
* [**API Reference**](/api/authentication) - Explore the API
* [**Security Best Practices**](/security/best-practices) - Secure your integration
* [**Bridge Integration**](/guides/bridge-integration) - Connect your backend
---
---
url: /operations/blogCreateCategoryBulk.md
---
Create several blog categories in one request. Existing slugs are skipped.
Auth: session + admin.
## Parameters
None.
## Request Body
```json
{
"names": ["Engineering", "Design"],
"lang": "en"
}
```
## Response 201
```json
{
"data": [
{ "id": "cat_2", "name": "Engineering", "slug": "engineering" }
],
"user_context": { "authenticated": true, "user_type": "admin" },
"meta": {}
}
```
## Response Errors
* `400` invalid payload
* `401` missing session
* `403` missing admin role
* `429` `RATE_LIMIT_EXCEEDED`
## Notes
* Rate limit: `post` bucket, 10 requests / 3600s by default. A session that can publish (`admin`, `superadmin`, `author`, `editor`, or the roles in `BLOG_ALLOWED_POST_ROLES` and `BLOG_ADMIN_ROLES`) is not counted. Otherwise `429` `RATE_LIMIT_EXCEEDED`. See [Rate limits](/api/blog#rate-limits).
---
---
url: /operations/blogCreateCategory.md
---
Create a blog category.
Auth: session + admin.
## Parameters
None.
## Request Body
```json
{
"name": "Engineering",
"slug": "engineering"
}
```
## Response 200
```json
{
"data": { "id": "cat_2", "name": "Engineering", "slug": "engineering" },
"user_context": { "authenticated": true, "user_type": "admin" },
"meta": {}
}
```
## Response Errors
* `400` invalid category payload
* `401` missing session
* `403` missing admin role
* `429` `RATE_LIMIT_EXCEEDED`
## Notes
* Rate limit: `post` bucket, 10 requests / 3600s by default. A session that can publish (`admin`, `superadmin`, `author`, `editor`, or the roles in `BLOG_ALLOWED_POST_ROLES` and `BLOG_ADMIN_ROLES`) is not counted. Otherwise `429` `RATE_LIMIT_EXCEEDED`. See [Rate limits](/api/blog#rate-limits).
* Use this to add new taxonomy groups.
* Category names should be unique and human-friendly.
---
---
url: /operations/blogCreateComment.md
---
Create a comment on a blog post.
Auth: conditional.
## Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| `id` | path | string | Yes | Post id |
## Request Body
```json
{
"body": "Nice article"
}
```
## Response 200
```json
{
"data": { "id": "com_2", "body": "Nice article" },
"user_context": { "authenticated": true },
"meta": {}
}
```
## Response Errors
* `400` invalid comment payload
* `403` comments not allowed for caller
* `404` post not found
* `429` `RATE_LIMIT_EXCEEDED`
## Notes
* Rate limit: `comment` bucket, 30 requests / 3600s by default. Every caller is counted, including publishers. Over the limit returns `429` `RATE_LIMIT_EXCEEDED`. See [Rate limits](/api/blog#rate-limits).
* The caller must be allowed to comment by the post visibility rules.
* Use this from logged-in or guest flows depending on configuration.
---
---
url: /operations/blogCreatePost.md
---
Create a new blog post.
Auth: session + writer role.
## Body
* title
* slug
* body
* body\_format
* visibility
* `lang` — ISO 639-1 code, for example `"lang": "es"`. Omitted means the default language. See [Languages](/api/blog#languages).
* `post_type` (CPT)
* `custom_fields` (CPT)
## Parameters
None.
## Request Body
```json
{
"title": "Why modular docs matter",
"slug": "why-modular-docs-matter",
"body": "# Why modular docs matter",
"body_format": "markdown",
"visibility": "public",
"lang": "es",
"post_type": "case-study",
"custom_fields": { "client": "Acme" }
}
```
## Response 200
```json
{
"data": {
"id": "post_2",
"slug": "why-modular-docs-matter",
"status": "draft",
"post_type": "case-study",
"custom_fields": { "client": "Acme" }
},
"user_context": { "authenticated": true, "user_type": "writer" },
"meta": { "cached": false }
}
```
## Response Errors
* `400` invalid post payload (`CUSTOM_FIELDS_*`, `MAX_PER_AUTHOR`, …)
* `401` missing session
* `403` missing writer role or `APPROVAL_REQUIRED` on publish
* `503` Blog / related module disabled
* `429` `RATE_LIMIT_EXCEEDED`
## Notes
* Rate limit: `post` bucket, 10 requests / 3600s by default. A session that can publish (`admin`, `superadmin`, `author`, `editor`, or the roles in `BLOG_ALLOWED_POST_ROLES` and `BLOG_ADMIN_ROLES`) is not counted. Otherwise `429` `RATE_LIMIT_EXCEEDED`. See [Rate limits](/api/blog#rate-limits).
* Use this when creating draft content.
* Supports optional comments, reactions, excerpt, and scheduling fields.
* When CPT is enabled, send `post_type` (defaults from `POST_TYPES_DEFAULT_TYPE`) and `custom_fields` validated against the type `field_schema`.
* `post_type` is locked after create. Behaviors may enforce approval, scheduling, password visibility, and `max_per_author`.
---
---
url: /operations/blogCreateTag.md
---
Create a blog tag.
Auth: session + admin.
## Parameters
None.
## Request Body
```json
{
"name": "Product",
"slug": "product",
"lang": "en"
}
```
`lang` is optional. When omitted, the tag is stored as `BLOG_DEFAULT_LANG`. Send the post language when the tag is created from that post.
## Response 200
```json
{
"data": { "id": "tag_2", "name": "Product", "slug": "product" },
"user_context": { "authenticated": true, "user_type": "admin" },
"meta": {}
}
```
## Response Errors
* `400` invalid tag payload
* `401` missing session
* `403` missing admin role
* `429` `RATE_LIMIT_EXCEEDED`
## Notes
* Rate limit: `post` bucket, 10 requests / 3600s by default. A session that can publish (`admin`, `superadmin`, `author`, `editor`, or the roles in `BLOG_ALLOWED_POST_ROLES` and `BLOG_ADMIN_ROLES`) is not counted. Otherwise `429` `RATE_LIMIT_EXCEEDED`. See [Rate limits](/api/blog#rate-limits).
* Use this for editorial tags and classification.
* Keep tag slugs short and stable.
---
---
url: /operations/blogCreateTagBulk.md
---
Create several blog tags in one request. Existing slugs are skipped.
Auth: session + admin.
## Parameters
None.
## Request Body
```json
{
"names": ["release", "api"],
"lang": "es"
}
```
`lang` is optional. When omitted, every new tag is stored as `BLOG_DEFAULT_LANG`.
## Response 201
```json
{
"data": [
{ "id": "tag_2", "name": "release", "slug": "release" }
],
"user_context": { "authenticated": true, "user_type": "admin" },
"meta": {}
}
```
## Response Errors
* `400` invalid payload
* `401` missing session
* `403` missing admin role
* `429` `RATE_LIMIT_EXCEEDED`
## Notes
* Rate limit: `post` bucket, 10 requests / 3600s by default. A session that can publish (`admin`, `superadmin`, `author`, `editor`, or the roles in `BLOG_ALLOWED_POST_ROLES` and `BLOG_ADMIN_ROLES`) is not counted. Otherwise `429` `RATE_LIMIT_EXCEEDED`. See [Rate limits](/api/blog#rate-limits).
---
---
url: /operations/blogCreateTranslation.md
---
Create a translation for a blog post.
Auth: session + writer role.
## Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| `id` | path | string | Yes | Post id |
## Request Body
```json
{
"lang": "es",
"title": "Hola mundo",
"body": "# Hola"
}
```
## Response 200
```json
{
"data": { "id": "post_2", "lang": "es", "created": true },
"user_context": { "authenticated": true, "user_type": "writer" },
"meta": {}
}
```
## Response Errors
* `400` invalid translation payload
* `401` missing session
* `403` missing writer role
* `404` post not found
* `429` `RATE_LIMIT_EXCEEDED`
## Notes
* Rate limit: `post` bucket, 10 requests / 3600s by default. A session that can publish (`admin`, `superadmin`, `author`, `editor`, or the roles in `BLOG_ALLOWED_POST_ROLES` and `BLOG_ADMIN_ROLES`) is not counted. Otherwise `429` `RATE_LIMIT_EXCEEDED`. See [Rate limits](/api/blog#rate-limits).
* Use this to publish localised versions of the same post.
* Keep the source language and translated slug aligned.
---
---
url: /operations/adminCreateUser.md
---
---
---
url: /operations/postTypesCreate.md
---
Create a user-defined post type.
Auth: session + post-types admin role (+ origin checks as configured).
## Parameters
None.
## Request Body
```json
{
"type_key": "case-study",
"type_name": "Case Study",
"description": "Customer success stories",
"slug_prefix": "case-studies",
"field_schema": [
{
"name": "client",
"label": "Client",
"type": "text",
"required": true
}
],
"behaviors": {
"requires_approval": true,
"enables_seo": true
},
"is_active": true,
"sort_order": 10
}
```
## Response 200
```json
{
"data": {
"id": "pt_2",
"type_key": "case-study",
"type_name": "Case Study",
"is_active": true,
"is_built_in": false
}
}
```
## Response Errors
* `400` invalid payload or `type_key`
* `401` missing session
* `403` insufficient role or `USER_TYPES_DISABLED`
* `503` `MODULE_DISABLED`
## Notes
* `type_key` is immutable after create.
* Returns `403 USER_TYPES_DISABLED` when `POST_TYPES_ALLOW_USER_TYPES=false`.
* Admin roles: `POST_TYPES_ADMIN_ROLES` → `BLOG_ADMIN_ROLES` → `admin,superadmin`.
---
---
url: /api/token-create.md
---
---
---
url: /operations/createTokenLogin.md
---
---
---
url: /instance-setup/creating-instance.md
---
# Creating a Flowless Instance
Learn how to create and configure your first Flowless instance on Pubflow.com in just a few minutes.
***
## Prerequisites
Before creating a Flowless instance, you'll need:
* A Pubflow account ([Sign up here](https://pubflow.com/signup))
* Basic understanding of your application's requirements
***
## Step 1: Access the Pubflow Dashboard
1. **Log in** to [Pubflow.com](https://pubflow.com/login)
2. **Navigate** to the Dashboard
3. **Click** on "Create New Instance" or "New Service"
***
## Step 2: Select Flowless
1. From the service selection screen, choose **Flowless**
2. You'll see a brief description of what Flowless provides
3. Click **"Continue"** to proceed with configuration
***
## Step 3: Configure Your Instance
### Basic Configuration
#### Instance Name
* Choose a unique, descriptive name
* This will be part of your instance URL
* Examples: `my-app-auth`, `production-auth`, `staging-auth`
* **URL Format**: `https://your-instance-name.pubflow.com`
```
Instance Name: my-app-auth
Instance URL: https://my-app-auth.pubflow.com
```
::: tip
Use different instances for different environments:
* `my-app-dev` for development
* `my-app-staging` for staging
* `my-app-prod` for production
:::
#### Region Selection
Choose the region closest to your users for optimal performance:
| Region | Location | Best For |
|--------|----------|----------|
| `us_east` | Virginia, USA | North America |
| `us_west` | California, USA | West Coast USA |
| `eu_west` | Ireland | Europe |
| `eu_central` | Frankfurt, Germany | Central Europe |
| `ap_southeast` | Singapore | Asia Pacific |
| `ap_northeast` | Tokyo, Japan | East Asia |
::: tip Multi-Region & Custom Deployments
Flowless can be deployed across **multiple regions** simultaneously with automatic load balancing for global applications. Need a specific region not listed? **Contact us** to request a new region deployment or discuss custom infrastructure requirements. There are no limits - we can deploy Flowless wherever your users are.
📧 [Contact Support](mailto:support@pubflow.com) for multi-region or custom deployments.
:::
::: warning
Region cannot be changed after creation. Choose carefully! (Create new deployment)
:::
***
## Step 4: Initial Settings
### Database Selection
Flowless automatically provisions a database for you. Choose your preferred database:
* **PostgreSQL** (Recommended) - Best performance and features
* **MySQL** - Wide compatibility
* **LibSQL** - Serverless, edge-optimized
::: tip
PostgreSQL is recommended for production use due to better performance and feature support.
:::
### Security Settings
#### Session Duration
* **Default**: 7 days
* **Range**: 1 hour to 30 days
* **Recommendation**: 7 days for web, 30 days for mobile
#### Email Verification
* **Required**: Users must verify email before login
* **Optional**: Users can login without verification
* **Disabled**: No verification emails sent
#### Password Requirements
* **Minimum Length**: 8-32 characters (default: 8)
* **Require Uppercase**: Yes/No (default: Yes)
* **Require Numbers**: Yes/No (default: Yes)
* **Require Special Characters**: Yes/No (default: Yes)
***
## Step 5: Review and Create
1. **Review** all your settings
2. **Confirm** your configuration
3. **Click** "Create Instance"
### Provisioning
The instance creation process takes approximately **30-60 seconds**:
```
✓ Creating database...
✓ Provisioning servers...
✓ Configuring security...
✓ Setting up email service...
✓ Generating credentials...
✓ Instance ready!
```
***
## Step 6: Get Your Credentials
Once created, you'll receive:
### Instance URL
```
https://your-instance-name.pubflow.com
```
### Bridge Secret
```
bridge_secret_abc123xyz789
```
::: danger
**Keep your Bridge Secret secure!**
* Never commit it to version control
* Store it in environment variables
* Rotate it regularly
* Use different secrets for dev/staging/prod
:::
### Admin API Key (Optional)
```
admin_key_def456uvw012
```
***
## Step 7: Test Your Instance
Verify your instance is working:
```bash
# Health check
curl https://your-instance-name.pubflow.com/test/health
# Expected response
{
"success": true,
"data": {
"status": "healthy",
"version": "1.0.0",
"uptime": 123
}
}
```
***
## Step 8: Configure Environment Variables
Add these to your application:
### Frontend (.env)
```bash
# Flowless instance URL
VITE_FLOWLESS_URL=https://your-instance-name.pubflow.com
# or for Next.js
NEXT_PUBLIC_FLOWLESS_URL=https://your-instance-name.pubflow.com
# or for Expo
EXPO_PUBLIC_FLOWLESS_URL=https://your-instance-name.pubflow.com
```
### Backend (.env)
```bash
# Flowless instance URL
FLOWLESS_URL=https://your-instance-name.pubflow.com
# Bridge Secret (KEEP SECURE!)
BRIDGE_SECRET=bridge_secret_abc123xyz789
# Validation mode (STANDARD, ADVANCED, STRICT)
VALIDATION_MODE=STANDARD
```
***
## Next Steps
Now that your instance is created:
1. [**Configure Your Instance**](/instance-setup/configuration) - Set up email, OAuth, etc.
2. [**Environment Variables**](/instance-setup/environment) - Complete environment setup
3. [**Make Your First API Call**](/getting-started#step-2-make-your-first-api-call) - Test the API
4. [**Integrate Your Backend**](/guides/bridge-integration) - Connect Flowfull
***
## Common Issues
### "Instance name already taken"
* Choose a different, unique name
* Instance names are globally unique across all Pubflow users
### "Region unavailable"
* Some regions may be temporarily unavailable
* Choose an alternative region
* Contact support for region-specific requirements
***
## Managing Your Instance
### Viewing Instance Details
1. Go to Pubflow Dashboard
2. Click on your instance name
3. View URL, status, usage, and settings
### Deleting an Instance
::: danger
Deleting an instance is **permanent** and cannot be undone!
:::
1. Go to Instance Settings
2. Scroll to "Danger Zone"
3. Click "Delete Instance"
4. Type instance name to confirm
5. All data will be permanently deleted
***
## Need Help?
* 📚 [Configuration Guide](/instance-setup/configuration)
* 💬 [Community Forum](https://community.pubflow.com)
* 📧 [Support](mailto:support@pubflow.com)
---
---
url: /monitoring/dashboard.md
---
# Dashboard
Monitor your Flowless instance through the Pubflow dashboard with real-time metrics, analytics, and insights.
***
## Accessing the Dashboard
1. Log in to [Pubflow.com](https://pubflow.com)
2. Navigate to your Flowless instance
3. Click on **"Dashboard"** or **"Monitoring"**
***
## Overview
The dashboard provides a comprehensive view of your Flowless instance's health, usage, and performance.
### Key Metrics
```
┌─────────────────────────────────────────────────────────┐
│ FLOWLESS DASHBOARD │
├─────────────────────────────────────────────────────────┤
│ │
│ 📊 Active Users: 1,234 🔐 Sessions: 5,678 │
│ 📈 API Calls: 45.2K ⚡ Avg Response: 42ms │
│ ✉️ Emails Sent: 892 🚫 Rate Limits: 12 │
│ ⚠️ Errors: 3 (0.01%) ✅ Uptime: 99.98% │
│ │
└─────────────────────────────────────────────────────────┘
```
***
## Real-Time Metrics
### Active Users
**Definition**: Users who have logged in within the last 30 days
**Metrics**:
* Total active users
* New users (last 7 days)
* User growth rate
* User retention rate
**Chart**: Line graph showing daily active users over time
### Active Sessions
**Definition**: Valid, non-expired sessions
**Metrics**:
* Total active sessions
* Sessions per user (average)
* Session creation rate
* Session expiration rate
**Chart**: Real-time session count with 5-minute intervals
### API Calls
**Definition**: Total API requests to your Flowless instance
**Metrics**:
* Total API calls (today, this week, this month)
* Calls per endpoint
* Success rate
* Error rate
**Chart**: Bar chart showing API calls by endpoint
### Response Time
**Definition**: Average time to process API requests
**Metrics**:
* Average response time (p50)
* 95th percentile (p95)
* 99th percentile (p99)
* Slowest endpoint
**Chart**: Line graph showing response time over time
***
## Usage Statistics
### Authentication Activity
```
┌─────────────────────────────────────────┐
│ AUTHENTICATION ACTIVITY │
├─────────────────────────────────────────┤
│ │
│ Registrations: 234 (↑ 12%) │
│ Logins: 1,456 (↑ 8%) │
│ Failed Logins: 23 (↓ 5%) │
│ Password Resets: 12 (→ 0%) │
│ Email Verifications: 89 (↑ 15%) │
│ │
└─────────────────────────────────────────┘
```
### Social Authentication
```
┌─────────────────────────────────────────┐
│ SOCIAL AUTHENTICATION │
├─────────────────────────────────────────┤
│ │
│ Google: 456 logins (62%) │
│ Facebook: 189 logins (26%) │
│ GitHub: 67 logins (9%) │
│ Twitter: 23 logins (3%) │
│ │
└─────────────────────────────────────────┘
```
### Email Service
```
┌─────────────────────────────────────────┐
│ EMAIL SERVICE │
├─────────────────────────────────────────┤
│ │
│ Verification Emails: 234 │
│ Password Reset: 12 │
│ Welcome Emails: 234 │
│ Delivery Rate: 99.5% │
│ Bounce Rate: 0.3% │
│ │
└─────────────────────────────────────────┘
```
***
## Performance Monitoring
### System Health
```
┌─────────────────────────────────────────┐
│ SYSTEM HEALTH │
├─────────────────────────────────────────┤
│ │
│ Status: ✅ Healthy │
│ Uptime: 99.98% │
│ CPU Usage: 23% │
│ Memory Usage: 45% │
│ Database: ✅ Connected │
│ Redis Cache: ✅ Connected │
│ │
└─────────────────────────────────────────┘
```
### Error Tracking
```
┌─────────────────────────────────────────┐
│ ERROR TRACKING │
├─────────────────────────────────────────┤
│ │
│ Total Errors: 3 (0.01%) │
│ 4xx Errors: 2 │
│ 5xx Errors: 1 │
│ Rate Limit Hits: 12 │
│ │
│ Recent Errors: │
│ • 401 Unauthorized (2x) │
│ • 500 Internal Error (1x) │
│ │
└─────────────────────────────────────────┘
```
***
## Security Monitoring
### Rate Limiting
```
┌─────────────────────────────────────────┐
│ RATE LIMITING │
├─────────────────────────────────────────┤
│ │
│ Rate Limit Hits: 12 │
│ Blocked IPs: 2 │
│ Top Offenders: │
│ • 192.168.1.100 (5 hits) │
│ • 10.0.0.50 (3 hits) │
│ │
└─────────────────────────────────────────┘
```
### Failed Login Attempts
```
┌─────────────────────────────────────────┐
│ FAILED LOGIN ATTEMPTS │
├─────────────────────────────────────────┤
│ │
│ Total Failed: 23 │
│ Unique IPs: 8 │
│ Potential Attacks: 1 │
│ │
│ Top Failed IPs: │
│ • 203.0.113.45 (12 attempts) │
│ • 198.51.100.23 (5 attempts) │
│ │
└─────────────────────────────────────────┘
```
***
## Billing and Usage
### Current Plan
```
┌─────────────────────────────────────────┐
│ CURRENT PLAN │
├─────────────────────────────────────────┤
│ │
│ Plan: Pro │
│ Price: $29/month │
│ Billing Cycle: Monthly │
│ Next Billing: Jan 7, 2026 │
│ │
└─────────────────────────────────────────┘
```
### Usage Limits
```
┌─────────────────────────────────────────┐
│ USAGE LIMITS │
├─────────────────────────────────────────┤
│ │
│ Active Users: 1,234 / 10,000 │
│ ████░░░░░░░░░░░░░░░░░░░░░░░░ 12% │
│ │
│ API Calls: 45.2K / 1M │
│ ████░░░░░░░░░░░░░░░░░░░░░░░░ 4.5% │
│ │
│ Emails: 892 / 10K │
│ ████░░░░░░░░░░░░░░░░░░░░░░░░ 8.9% │
│ │
└─────────────────────────────────────────┘
```
***
## Alerts and Notifications
### Active Alerts
```
┌─────────────────────────────────────────┐
│ ACTIVE ALERTS │
├─────────────────────────────────────────┤
│ │
│ ⚠️ High error rate (0.5%) │
│ Triggered: 2 hours ago │
│ │
│ ℹ️ Approaching user limit (80%) │
│ Triggered: 1 day ago │
│ │
└─────────────────────────────────────────┘
```
### Alert Configuration
Configure alerts for:
* High error rate (> 1%)
* Slow response time (> 500ms)
* Usage limits (80%, 90%, 95%)
* Failed login attempts (> 10/min)
* System downtime
***
## Export Data
### Available Exports
* **User List**: CSV export of all users
* **Session Data**: CSV export of active sessions
* **API Logs**: JSON export of API calls
* **Analytics**: PDF report of usage statistics
### Export Options
```typescript
// Export users
GET /admin/export/users?format=csv
// Export sessions
GET /admin/export/sessions?format=csv
// Export logs
GET /admin/export/logs?format=json&start_date=2025-12-01&end_date=2025-12-07
```
***
## Next Steps
* [**Analytics**](/monitoring/analytics) - Detailed analytics and insights
* [**Logs**](/monitoring/logs) - View and search logs
* [**Alerts**](/monitoring/alerts) - Configure alerts and notifications
---
---
url: /operations/twoFactorDelete.md
---
---
---
url: /operations/blogDeleteCategory.md
---
## Notes
* Rate limit: `post` bucket, 10 requests / 3600s by default. A session that can publish (`admin`, `superadmin`, `author`, `editor`, or the roles in `BLOG_ALLOWED_POST_ROLES` and `BLOG_ADMIN_ROLES`) is not counted. Otherwise `429` `RATE_LIMIT_EXCEEDED`. See [Rate limits](/api/blog#rate-limits).
---
---
url: /operations/blogDeleteComment.md
---
Delete a blog comment.
Auth: session.
## Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| `id` | path | string | Yes | Post id |
| `commentId` | path | string | Yes | Comment id |
## Request Body
None.
## Response 200
```json
{
"data": { "id": "com_2", "deleted": true },
"user_context": { "authenticated": true },
"meta": {}
}
```
## Response Errors
* `401` missing session
* `403` not allowed
* `404` comment not found
* `429` `RATE_LIMIT_EXCEEDED`
## Notes
* Rate limit: `comment` bucket, 30 requests / 3600s by default. Every caller is counted, including publishers. Over the limit returns `429` `RATE_LIMIT_EXCEEDED`. See [Rate limits](/api/blog#rate-limits).
* Supports author deletion and moderation cleanup.
* Use this instead of hard deleting unrelated records.
---
---
url: /operations/blogDeleteFeaturedImage.md
---
## Notes
* Rate limit: `post` bucket, 10 requests / 3600s by default. A session that can publish (`admin`, `superadmin`, `author`, `editor`, or the roles in `BLOG_ALLOWED_POST_ROLES` and `BLOG_ADMIN_ROLES`) is not counted. Otherwise `429` `RATE_LIMIT_EXCEEDED`. See [Rate limits](/api/blog#rate-limits).
---
---
url: /operations/blogDeletePost.md
---
Delete a blog post.
Auth: session + owner/admin.
## Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| `id` | path | string | Yes | Post id |
## Request Body
None.
## Response 200
```json
{
"data": { "id": "post_2", "deleted": true },
"user_context": { "authenticated": true },
"meta": {}
}
```
## Response Errors
* `401` missing session
* `403` not owner/admin
* `404` post not found
* `429` `RATE_LIMIT_EXCEEDED`
## Notes
* Rate limit: `post` bucket, 10 requests / 3600s by default. A session that can publish (`admin`, `superadmin`, `author`, `editor`, or the roles in `BLOG_ALLOWED_POST_ROLES` and `BLOG_ADMIN_ROLES`) is not counted. Otherwise `429` `RATE_LIMIT_EXCEEDED`. See [Rate limits](/api/blog#rate-limits).
* Use this for permanent removal or admin cleanup.
* If soft delete is enabled, the underlying system may preserve the record.
---
---
url: /operations/blogDeleteTag.md
---
## Notes
* Rate limit: `post` bucket, 10 requests / 3600s by default. A session that can publish (`admin`, `superadmin`, `author`, `editor`, or the roles in `BLOG_ALLOWED_POST_ROLES` and `BLOG_ADMIN_ROLES`) is not counted. Otherwise `429` `RATE_LIMIT_EXCEEDED`. See [Rate limits](/api/blog#rate-limits).
---
---
url: /operations/blogDeleteTranslation.md
---
Delete a blog translation.
Auth: session + owner/admin.
## Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| `id` | path | string | Yes | Post id |
| `lang` | path | string | Yes | Language code |
## Request Body
None.
## Response 200
```json
{
"data": { "id": "post_2", "lang": "es", "deleted": true },
"user_context": { "authenticated": true },
"meta": {}
}
```
## Response Errors
* `401` missing session
* `403` not owner/admin
* `404` translation not found
* `429` `RATE_LIMIT_EXCEEDED`
## Notes
* Rate limit: `post` bucket, 10 requests / 3600s by default. A session that can publish (`admin`, `superadmin`, `author`, `editor`, or the roles in `BLOG_ALLOWED_POST_ROLES` and `BLOG_ADMIN_ROLES`) is not counted. Otherwise `429` `RATE_LIMIT_EXCEEDED`. See [Rate limits](/api/blog#rate-limits).
* Use this to remove stale or incorrect translations.
* Prefer deleting only the language variant, not the base post.
---
---
url: /operations/postTypesDelete.md
---
Delete a user-defined post type.
Auth: session + post-types admin role.
## Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| `key` | path | string | Yes | `type_key` |
## Request Body
None.
## Response 200
```json
{
"data": { "deleted": true, "type_key": "case-study" }
}
```
## Response Errors
* `400` built-in type, or posts still exist for this type
* `401` missing session
* `403` insufficient role
* `404` type not found
* `503` `MODULE_DISABLED`
## Notes
* Built-in types cannot be deleted.
* Reassign or delete posts of this type before deleting the definition.
---
---
url: /operations/deleteProfilePicture.md
---
---
---
url: /operations/moduleHubDiscover.md
---
---
---
url: /instance-setup/email.md
---
# Email Setup
Configure email service for your Flowless instance to send verification emails, password resets, and notifications.
***
## Overview
Flowless includes an integrated email service powered by **ZeptoMail** for sending:
* Email verification
* Password reset
* Welcome emails
* Account notifications
***
## Default Email Service
### ZeptoMail (Default Provider)
Flowless uses **ZeptoMail** as the default email provider. To enable email functionality:
1. Log in to [Pubflow Platform](https://pubflow.com)
2. Navigate to your Flowless instance
3. Go to **Settings** → **Email**
4. Provide your **ZeptoMail API Key**
Once configured, emails will work automatically for:
* Email verification
* Password reset
* Welcome emails
* Account notifications
::: tip
You can obtain a ZeptoMail API key from [ZeptoMail Dashboard](https://www.zoho.com/zeptomail/). ZeptoMail offers generous free tiers and reliable email delivery.
:::
***
## Email Configuration
### Access Email Settings
1. Log in to [Pubflow Platform](https://pubflow.com)
2. Navigate to your Flowless instance
3. Go to **Settings** → **Email**
***
## Email Templates
### Available Templates
Flowless provides customizable email templates:
#### 1. Email Verification
**Subject**: Verify your email address
**Content**:
```
Hi {{name}},
Welcome to {{app_name}}!
Please verify your email address by clicking the link below:
{{verification_link}}
This link will expire in 24 hours.
If you didn't create an account, you can safely ignore this email.
Thanks,
The {{app_name}} Team
```
#### 2. Password Reset
**Subject**: Reset your password
**Content**:
```
Hi {{name}},
We received a request to reset your password for {{app_name}}.
Click the link below to reset your password:
{{reset_link}}
This link will expire in 1 hour.
If you didn't request a password reset, you can safely ignore this email.
Thanks,
The {{app_name}} Team
```
#### 3. Welcome Email
**Subject**: Welcome to {{app\_name}}!
**Content**:
```
Hi {{name}},
Welcome to {{app_name}}! We're excited to have you on board.
Here are some helpful links to get started:
- Dashboard: {{dashboard_link}}
- Documentation: {{docs_link}}
- Support: {{support_link}}
If you have any questions, feel free to reach out to our support team.
Thanks,
The {{app_name}} Team
```
***
## Customizing Email Templates
### Template Variables
Available variables in all templates:
| Variable | Description | Example |
|----------|-------------|---------|
| `{{name}}` | User's first name | John |
| `{{email}}` | User's email | user@example.com |
| `{{app_name}}` | Your app name | My App |
| `{{verification_link}}` | Email verification link | https://... |
| `{{reset_link}}` | Password reset link | https://... |
| `{{dashboard_link}}` | Dashboard URL | https://app.myapp.com |
| `{{docs_link}}` | Documentation URL | https://docs.myapp.com |
| `{{support_link}}` | Support URL | https://support.myapp.com |
### Edit Templates
1. Go to **Settings** → **Email** → **Templates**
2. Select the template to edit
3. Modify the subject and content
4. Use `{{variables}}` for dynamic content
5. Preview the template
6. Save changes
***
## Email Settings
### Sender Information
Configure the sender details:
```json
{
"from_name": "My App",
"from_email": "noreply@myapp.com",
"reply_to": "support@myapp.com"
}
```
::: tip
Use a professional email address for better deliverability.
:::
### Email Verification
Configure email verification behavior:
```json
{
"verification_required": true,
"verification_link_expiry_hours": 24,
"send_welcome_email": true
}
```
**Options**:
* **Required**: Users must verify before login
* **Optional**: Users can login without verification
* **Disabled**: No verification emails sent
### Password Reset
Configure password reset settings:
```json
{
"reset_link_expiry_hours": 1,
"max_reset_attempts": 3
}
```
***
## Custom SMTP (Enterprise)
### Configure Custom SMTP
For Enterprise plans, you can use your own SMTP server:
```json
{
"smtp_host": "smtp.gmail.com",
"smtp_port": 587,
"smtp_secure": true,
"smtp_user": "your-email@gmail.com",
"smtp_password": "your-app-password",
"from_email": "noreply@yourdomain.com",
"from_name": "Your App"
}
```
### Supported SMTP Providers
* **Gmail**: smtp.gmail.com:587
* **SendGrid**: smtp.sendgrid.net:587
* **Mailgun**: smtp.mailgun.org:587
* **AWS SES**: email-smtp.us-east-1.amazonaws.com:587
* **Custom**: Any SMTP server
### Gmail Setup
1. Enable 2-factor authentication
2. Generate an App Password
3. Use App Password in SMTP settings
```json
{
"smtp_host": "smtp.gmail.com",
"smtp_port": 587,
"smtp_secure": true,
"smtp_user": "your-email@gmail.com",
"smtp_password": "your-app-password"
}
```
***
## Testing Email
### Send Test Email
1. Go to **Settings** → **Email** → **Test**
2. Enter a test email address
3. Select template to test
4. Click **Send Test Email**
5. Check your inbox
### Test via API
```bash
curl -X POST https://your-instance.pubflow.com/test/send-email \
-H "Content-Type: application/json" \
-H "X-Admin-Key: your_admin_key" \
-d '{
"to": "test@example.com",
"template": "verification",
"data": {
"name": "Test User",
"verification_link": "https://example.com/verify"
}
}'
```
***
## Email Deliverability
### Best Practices
1. **Use a custom domain** (not @gmail.com)
2. **Set up SPF records**
3. **Set up DKIM records**
4. **Set up DMARC records**
5. **Monitor bounce rates**
6. **Keep email list clean**
### DNS Records
Add these DNS records for better deliverability:
#### SPF Record
```
Type: TXT
Name: @
Value: v=spf1 include:_spf.zeptomail.com ~all
```
#### DKIM Record
```
Type: TXT
Name: zeptomail._domainkey
Value: [Provided by ZeptoMail]
```
#### DMARC Record
```
Type: TXT
Name: _dmarc
Value: v=DMARC1; p=none; rua=mailto:dmarc@yourdomain.com
```
***
## Monitoring Email
### Email Analytics
View email statistics in the dashboard:
* **Sent**: Total emails sent
* **Delivered**: Successfully delivered
* **Bounced**: Failed deliveries
* **Opened**: Email opens (if tracking enabled)
* **Clicked**: Link clicks (if tracking enabled)
### Email Logs
View detailed email logs:
```
┌─────────────────────────────────────────────────────────┐
│ EMAIL LOGS │
├─────────────────────────────────────────────────────────┤
│ │
│ 2025-12-07 10:00:00 ✅ Verification sent │
│ To: user@example.com │
│ Status: Delivered │
│ │
│ 2025-12-07 09:45:00 ✅ Password reset sent │
│ To: another@example.com │
│ Status: Delivered │
│ │
│ 2025-12-07 09:30:00 ❌ Welcome email failed │
│ To: invalid@example.com │
│ Status: Bounced (Invalid email) │
│ │
└─────────────────────────────────────────────────────────┘
```
***
## Troubleshooting
### Emails Not Sending
1. **Check email settings** in dashboard
2. **Verify SMTP credentials** (if using custom SMTP)
3. **Check spam folder**
4. **Verify DNS records** (SPF, DKIM, DMARC)
5. **Check email logs** for errors
### Emails Going to Spam
1. **Set up SPF, DKIM, DMARC** records
2. **Use a custom domain** (not free email providers)
3. **Avoid spam trigger words** in subject/content
4. **Keep bounce rate low** (< 5%)
5. **Warm up your domain** (start with low volume)
### High Bounce Rate
1. **Validate email addresses** before sending
2. **Remove invalid emails** from your list
3. **Use double opt-in** for registrations
4. **Monitor bounce reports**
***
## Next Steps
* [**Social Auth Setup**](/instance-setup/social-auth) - Configure OAuth
* [**Email Verification Guide**](/guides/email-verification) - Implement verification
* [**Password Reset Guide**](/guides/password-reset) - Implement password reset
* [**Monitoring**](/monitoring/dashboard) - Monitor email delivery
---
---
url: /guides/email-verification.md
---
# Email Verification
::: warning COMING SOON
This page is under construction. Check back soon for complete documentation.
:::
Complete guide to implementing email verification for new users.
## Overview
This guide will cover:
* Sending verification emails
* Verification link handling
* Token validation
* Resending verification emails
* Verification status checking
***
## Coming Soon
Full implementation guide with:
* Verification email flow
* Frontend verification page
* Resend verification functionality
* Error handling
* Best practices
***
## Next Steps
* [**Email Setup**](/instance-setup/email) - Configure email service
* [**User Registration**](/guides/user-registration) - Registration guide
* [**Users API**](/api/users) - Email verification API
---
---
url: /api/token-verify-email.md
---
---
---
url: /operations/verifyTokenEmail.md
---
---
---
url: /instance-setup/environment.md
---
# Environment Variables
Complete guide to configuring environment variables for Flowless integration in your frontend and backend applications.
***
## Overview
Environment variables are used to configure your application's connection to Flowless and manage sensitive credentials securely.
::: info
**Flowless Instance Configuration**
Flowless instance settings (email, social auth, database, etc.) are managed through the **Pubflow Platform** dashboard. This guide covers environment variables for **your application** that integrates with Flowless.
:::
::: danger
**Never commit environment variables to version control!**
Always use `.env` files and add them to `.gitignore`.
:::
***
## Frontend Environment Variables
### React (Vite)
Create `.env` file in your React project root:
```bash
# Flowless instance URL
VITE_FLOWLESS_URL=https://your-instance-name.pubflow.com
# Optional: API base URL (your backend)
VITE_API_URL=https://api.yourdomain.com
# Optional: Environment
VITE_ENV=production
```
**Usage in code:**
```typescript
const FLOWLESS_URL = import.meta.env.VITE_FLOWLESS_URL;
const API_URL = import.meta.env.VITE_API_URL;
```
### Next.js
Create `.env.local` file in your Next.js project root:
```bash
# Flowless instance URL (public)
NEXT_PUBLIC_FLOWLESS_URL=https://your-instance-name.pubflow.com
# API URL (public)
NEXT_PUBLIC_API_URL=https://api.yourdomain.com
# Server-side only (not exposed to browser)
FLOWLESS_URL=https://your-instance-name.pubflow.com
BRIDGE_SECRET=bridge_secret_abc123xyz789
```
**Usage in code:**
```typescript
// Client-side
const FLOWLESS_URL = process.env.NEXT_PUBLIC_FLOWLESS_URL;
// Server-side only
const BRIDGE_SECRET = process.env.BRIDGE_SECRET;
```
### React Native (Expo)
Create `.env` file in your Expo project root:
```bash
# Flowless instance URL
EXPO_PUBLIC_FLOWLESS_URL=https://your-instance-name.pubflow.com
# API URL
EXPO_PUBLIC_API_URL=https://api.yourdomain.com
# Optional: Log mode
EXPO_PUBLIC_LOG_MODE=production
```
**Usage in code:**
```typescript
const FLOWLESS_URL = process.env.EXPO_PUBLIC_FLOWLESS_URL;
const API_URL = process.env.EXPO_PUBLIC_API_URL;
```
***
## Backend Environment Variables
### Node.js / Express / Hono
Create `.env` file in your backend project root:
```bash
# ============================================
# FLOWLESS CONFIGURATION
# ============================================
# Flowless instance URL
FLOWLESS_URL=https://your-instance-name.pubflow.com
# Bridge Secret (KEEP SECURE!)
BRIDGE_SECRET=bridge_secret_abc123xyz789
# Validation mode (STANDARD, ADVANCED, STRICT)
VALIDATION_MODE=STANDARD
# ============================================
# APPLICATION CONFIGURATION
# ============================================
# Server port
PORT=3000
# Environment
NODE_ENV=production
# API URL
API_URL=https://api.yourdomain.com
# Frontend URL (for CORS)
FRONTEND_URL=https://yourdomain.com
# ============================================
# DATABASE CONFIGURATION
# ============================================
# Database URL
DATABASE_URL=postgresql://user:password@localhost:5432/myapp
# ============================================
# CACHE CONFIGURATION
# ============================================
# Redis URL (optional)
REDIS_URL=redis://localhost:6379
# Trust token cache TTL (seconds)
TRUST_TOKEN_CACHE_TTL=300
# ============================================
# LOGGING
# ============================================
# Log level (DEBUG, INFO, WARN, ERROR)
LOG_LEVEL=INFO
# Log mode (development, production)
LOG_MODE=production
```
**Usage in code:**
```typescript
const FLOWLESS_URL = process.env.FLOWLESS_URL!;
const BRIDGE_SECRET = process.env.BRIDGE_SECRET!;
const VALIDATION_MODE = process.env.VALIDATION_MODE || 'STANDARD';
```
***
## Environment-Specific Configuration
### Development
`.env.development`
```bash
FLOWLESS_URL=https://dev-instance.pubflow.com
BRIDGE_SECRET=dev_bridge_secret_123
VALIDATION_MODE=STANDARD
NODE_ENV=development
LOG_LEVEL=DEBUG
```
### Staging
`.env.staging`
```bash
FLOWLESS_URL=https://staging-instance.pubflow.com
BRIDGE_SECRET=staging_bridge_secret_456
VALIDATION_MODE=ADVANCED
NODE_ENV=staging
LOG_LEVEL=INFO
```
### Production
`.env.production`
```bash
FLOWLESS_URL=https://prod-instance.pubflow.com
BRIDGE_SECRET=prod_bridge_secret_789
VALIDATION_MODE=STRICT
NODE_ENV=production
LOG_LEVEL=WARN
```
***
## Security Best Practices
### 1. Never Commit Secrets
Add to `.gitignore`:
```
# Environment variables
.env
.env.local
.env.development
.env.staging
.env.production
.env.*.local
```
### 2. Use Different Secrets per Environment
```bash
# ❌ Bad - same secret everywhere
BRIDGE_SECRET=bridge_secret_123
# ✅ Good - different secrets
# Dev: dev_bridge_secret_abc
# Staging: staging_bridge_secret_def
# Prod: prod_bridge_secret_xyz
```
### 3. Rotate Secrets Regularly
```bash
# Rotate every 90 days
# Old: bridge_secret_abc123
# New: bridge_secret_xyz789
```
### 4. Validate Required Variables
```typescript
function validateEnv() {
const required = [
'FLOWLESS_URL',
'BRIDGE_SECRET',
'DATABASE_URL',
];
for (const key of required) {
if (!process.env[key]) {
throw new Error(`Missing required environment variable: ${key}`);
}
}
}
validateEnv();
```
***
## Complete Example
### Frontend (.env)
```bash
VITE_FLOWLESS_URL=https://my-app.pubflow.com
VITE_API_URL=https://api.myapp.com
```
### Backend (.env)
```bash
# Flowless
FLOWLESS_URL=https://my-app.pubflow.com
BRIDGE_SECRET=bridge_secret_abc123xyz789
VALIDATION_MODE=STANDARD
# Server
PORT=3000
NODE_ENV=production
# Database
DATABASE_URL=postgresql://user:pass@localhost:5432/myapp
# Cache
REDIS_URL=redis://localhost:6379
TRUST_TOKEN_CACHE_TTL=300
# Logging
LOG_LEVEL=INFO
```
***
## Troubleshooting
### "Environment variable not found"
```typescript
// ❌ Wrong
const url = process.env.FLOWLESS_URL;
// ✅ Correct - with fallback
const url = process.env.FLOWLESS_URL || 'https://default.pubflow.com';
// ✅ Better - throw error if missing
const url = process.env.FLOWLESS_URL;
if (!url) throw new Error('FLOWLESS_URL not set');
```
### "Variables not loading"
1. Check `.env` file exists
2. Check `.env` is in project root
3. Check `dotenv` is imported before usage
4. Restart development server
***
## Next Steps
* [**Email Setup**](/instance-setup/email) - Configure email service
* [**Social Auth Setup**](/instance-setup/social-auth) - Set up OAuth
* [**Configuration**](/instance-setup/configuration) - Instance settings
* [**Getting Started**](/getting-started) - Start building
---
---
url: /api/authentication.md
---
# Flowless API Reference
Complete API documentation for Flowless Authentication Service. All endpoints use **snake\_case** for request/response fields.
## Module Reference
* [Modules overview](/api/modules) - Map of optional module surfaces
* [Module Hub API](/api/module-hub) - Install, dry-run, registry, status
* [Blog API](/api/blog) - Post system API with publishing, comments, and stats
* [Post Types API](/api/post-types) - Custom post type definitions and typed content helpers
* [Onboarding API](/api/onboarding) - First-run complete, acquisition (write-only), business fields
* [Privacy API](/api/privacy) - GDPR/CCPA/`privacy_region` under `/auth/user/me/privacy*`
* [Two-Factor API](/api/two-factor) - 2FA methods, verify, and session promotion
***
## 🚀 Quick Start
**Base URL:** `https://your-instance-name.pubflow.com`
**Authentication:** Most endpoints require `X-Session-ID` header or `X-Bridge-Secret` header (for bridge endpoints).
**Response Format:** All responses use snake\_case fields (e.g., `user_name`, `session_id`, `expires_at`).
***
## 📚 API Endpoints by Category
### 🔐 Authentication
Core authentication endpoints for user login, registration, and logout.
* [**POST /auth/login**](/operations/loginUser) - Login with email/username and password
* [**POST /auth/logout**](/operations/logoutUser) - Logout and invalidate session
* [**POST /auth/register/public**](/operations/registerPublic) - Register new user account (public registration)
* [**GET /auth/me**](/operations/getCurrentUser) - Get current authenticated user
***
### 👤 User Profile
Manage user profile information and profile pictures.
* [**PUT /auth/profile**](/operations/updateUserProfile) - Update user profile
* [**POST /auth/upload/picture**](/operations/uploadProfilePicture) - Upload profile picture
* [**DELETE /auth/upload/picture**](/operations/deleteProfilePicture) - Delete profile picture
***
### 🔑 Password Management
Password reset and change endpoints.
* [**POST /auth/password-reset/request**](/operations/requestPasswordReset) - Request password reset email
* [**POST /auth/password-reset/validate**](/operations/validatePasswordResetToken) - Validate reset token
* [**POST /auth/password-reset/complete**](/operations/completePasswordReset) - Complete password reset
* [**POST /auth/password-change/self**](/operations/changePassword) - Change own password (authenticated)
***
### ✉️ Email Verification
Email verification and resend endpoints.
* [**POST /auth/resend-verification**](/operations/resendVerification) - Resend verification email
* [**GET/POST /auth/email-change/verify**](/operations/confirmEmailChange) - Confirm one half of a pending login-email change (current inbox and new inbox; both are required)
* [**GET/POST /auth/email-change/cancel**](/operations/cancelEmailChange) - Reject a pending login-email change from the current inbox
***
### 🔗 Sessions
Session validation and bridge integration endpoints.
* [**GET /auth/validation**](/operations/validateSession) - Validate current session
* [**POST /auth/bridge/validate**](/operations/bridgeValidateSession) - Validate session for bridge integration
***
### 💾 Cache Management
Cache invalidation endpoints for efficient data synchronization.
* [**POST /auth/invalidate/me**](/operations/invalidateUserCache) - Invalidate user cache to force fresh data
***
### 🎫 Token Auth
Token-based authentication for passwordless login via email/SMS.
* [**POST /auth/token/login**](/operations/createTokenLogin) - Create verification token (email/SMS)
* [**POST /auth/token/validate**](/operations/validateToken) - Validate token (POST)
* [**GET /auth/token/validate**](/operations/validateTokenGet) - Validate token (GET)
* [**GET /auth/token/verify**](/operations/verifyTokenEmail) - Email verification link handler
***
### 🌐 Social Auth (BETA)
OAuth social authentication with Google, GitHub, Facebook, Apple, Discord, and Microsoft.
* [**GET /auth/social/{provider}/login**](/operations/socialLogin) - Start OAuth flow
* [**GET /auth/social/{provider}/callback**](/operations/socialCallback) - OAuth callback handler
* [**POST /auth/social/{provider}/login-api**](/operations/socialLoginApi) - API-based social login (mobile)
* [**GET /auth/social/providers**](/operations/getSocialProviders) - Get available providers
* [**GET /auth/social/accounts**](/operations/getSocialAccounts) - Get linked social accounts
* [**DELETE /auth/social/accounts/{provider}**](/operations/unlinkSocialAccount) - Unlink social account
***
### 👨💼 Admin
Admin-only endpoints for user management (requires admin or superadmin role).
* [**GET /auth/admin/users**](/operations/adminListUsers) - Search and list users
* [**POST /auth/admin/users**](/operations/adminCreateUser) - Create new user
* [**GET /auth/admin/users/{user\_id}**](/operations/adminGetUser) - Get user details
* [**PUT /auth/admin/users/{user\_id}**](/operations/adminUpdateUser) - Update user
* [**POST /auth/password-change/admin**](/operations/adminChangePassword) - Change user password (admin)
***
## 🔒 Authentication Methods
### Session Authentication
Most endpoints require a valid session. You can provide the session ID in multiple ways:
**1. Header (Recommended):**
```http
X-Session-ID: ses_xyz123456
```
**2. Query Parameter:**
```http
GET /auth/me?session_id=ses_xyz123456
POST /auth/profile?session_id=ses_xyz123456
```
**3. Cookie:**
```http
Cookie: session_id=ses_xyz123456
```
### Bridge Secret Authentication
Bridge endpoints (for integration) require the bridge secret:
```http
X-Bridge-Secret: your-bridge-secret-key
```
***
## 📊 Rate Limiting
All endpoints are rate-limited to prevent abuse:
| Endpoint Type | Limit | Window |
|--------------|-------|--------|
| Login | 5 attempts | 15 minutes |
| Registration | 3 attempts | 1 hour |
| Token Login | 10 attempts | 10 minutes |
| Token Validate | 20 attempts | 5 minutes |
| Social Login | 10 attempts | 15 minutes |
| Social API | 20 attempts | 10 minutes |
| Cache Invalidation | 10 attempts | 5 minutes |
| Admin Actions | 50 attempts | 10 minutes |
Rate limit headers are included in responses:
```http
X-RateLimit-Limit: 5
X-RateLimit-Remaining: 4
X-RateLimit-Reset: 1733570460
```
***
## 🎯 Common Response Codes
| Code | Description |
|------|-------------|
| `200` | Success |
| `400` | Bad Request - Invalid input or validation failed |
| `401` | Unauthorized - Invalid or missing authentication |
| `403` | Forbidden - Insufficient permissions |
| `404` | Not Found - Resource doesn't exist |
| `429` | Too Many Requests - Rate limit exceeded |
| `500` | Internal Server Error |
| `503` | Service Unavailable - Feature not configured |
***
## 🧪 Interactive Testing
Use the [**API Playground**](/playground) to test all endpoints interactively with your own server URL.
***
## 📖 Additional Resources
* [**Getting Started Guide**](/getting-started) - Setup and configuration
* [**Core Concepts**](/core-concepts) - Understanding Flowless architecture
* [**Instance Setup**](/instance-setup/creating-instance) - Deploy your own instance
* [**Social Auth Setup**](/instance-setup/social-auth) - Configure OAuth providers
---
---
url: /README.md
---
# Flowless Documentation
> Fully managed authentication service for modern applications
This is the official documentation for **Flowless**, the authentication backend service provided by Pubflow.
## 🚀 Quick Links
* **Live Documentation**: [docs.pubflow.com/flowless](https://docs.pubflow.com/flowless)
* **Create Instance**: [pubflow.com](https://pubflow.com)
* **Community**: [community.pubflow.com](https://community.pubflow.com)
* **Support**:
## 📚 Documentation Structure
```
.
├── index.md # Landing page
├── introduction.md # What is Flowless?
├── getting-started.md # Quick start guide
├── core-concepts.md # Core concepts
├── architecture.md # Architecture overview
├── instance-setup/ # Instance setup guides
│ ├── creating-instance.md
│ ├── configuration.md
│ ├── environment.md
│ ├── email.md
│ └── social-auth.md
├── modules/ # Module guides and product extensions
│ ├── index.md
│ ├── blog.md
│ └── two-factor.md
├── api/ # API reference
│ ├── authentication.md
│ ├── module-hub.md
│ ├── blog.md
│ ├── two-factor.md
│ ├── modules.md
│ ├── token-auth.md
│ ├── social-auth.md
│ ├── sessions.md
│ ├── users.md
│ └── admin.md
├── guides/ # Integration guides
│ ├── user-registration.md
│ ├── login-flow.md
│ ├── password-reset.md
│ ├── email-verification.md
│ ├── social-login.md
│ ├── session-management.md
│ ├── bridge-integration.md
│ └── testing.md
├── security/ # Security documentation
│ ├── authentication.md
│ ├── sessions.md
│ ├── rate-limiting.md
│ ├── validation.md
│ └── best-practices.md
├── monitoring/ # Monitoring and analytics
│ ├── dashboard.md
│ ├── analytics.md
│ ├── logs.md
│ └── alerts.md
├── llms.txt # LLM-friendly summary
└── llms-full.txt # Complete LLM documentation
```
## 🛠️ Development
### Prerequisites
* Node.js 18+
* npm or yarn
### Install Dependencies
```bash
npm install
```
### Run Development Server
```bash
npm run dev
```
The documentation will be available at `http://localhost:5173`
### Build for Production
```bash
npm run build
```
### Preview Production Build
```bash
npm run preview
```
## 📝 Contributing
We welcome contributions to improve the documentation!
### Guidelines
1. **Clarity**: Write clear, concise documentation
2. **Examples**: Include code examples for all concepts
3. **Accuracy**: Ensure all information is accurate and up-to-date
4. **Consistency**: Follow the existing style and structure
### Making Changes
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Test locally with `npm run dev`
5. Submit a pull request
## 🎨 Style Guide
### Writing Style
* Use **active voice**
* Write in **second person** ("you")
* Keep sentences **short and clear**
* Use **code examples** liberally
* Include **warnings** for security-critical information
### Code Examples
```typescript
// ✅ Good: Clear, commented, complete
async function login(email: string, password: string) {
const response = await fetch(`${FLOWLESS_URL}/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
});
const data = await response.json();
return data;
}
// ❌ Bad: Incomplete, no context
fetch('/auth/login', { body: data });
```
### Markdown Conventions
* Use `###` for main sections
* Use `####` for subsections
* Use **bold** for emphasis
* Use `code` for inline code
* Use code blocks with language tags
* Use tables for structured data
* Use admonitions (tip, warning, danger) for important notes
## 🔧 VitePress Configuration
The documentation uses VitePress with the following configuration:
* **Theme**: Default VitePress theme
* **Logo**: Pubflow logo from cloud.notside.com
* **Color**: #006AFF (Pubflow blue)
* **Font**: Roboto Slab
* **Search**: Local search enabled
## 📄 License
This documentation is licensed under AGPL-3.0.
Copyright © 2025 Pubflow, Inc.
## 🆘 Support
Need help with the documentation?
* **Issues**: [GitHub Issues](https://github.com/pubflow/flowless-docs/issues)
* **Discussions**: [GitHub Discussions](https://github.com/pubflow/flowless-docs/discussions)
* **Email**:
***
**Built with ❤️ by the Pubflow team**
---
---
url: /IMPLEMENTATION_STATUS.md
---
# Flowless Documentation - Implementation Status
> Last Updated: December 7, 2025
## 📊 Overall Progress
**Phase 1: Flowless Documentation** - **IN PROGRESS** (Week 1-2 of 6)
```
Progress: ████████░░░░░░░░░░░░░░░░░░░░ 35% Complete
```
***
## ✅ Completed Files
### Core Documentation (5/5) ✅
* \[x] `index.md` - Landing page with hero section
* \[x] `introduction.md` - What is Flowless?
* \[x] `getting-started.md` - Quick start guide
* \[x] `core-concepts.md` - Core concepts overview
* \[x] `architecture.md` - Architecture and design
### Configuration (2/2) ✅
* \[x] `.vitepress/config.mts` - VitePress configuration
* \[x] `package.json` - Dependencies and scripts
### Instance Setup (2/5) 🔄
* \[x] `instance-setup/creating-instance.md` - Creating instance guide
* \[x] `instance-setup/configuration.md` - Configuration guide
* \[ ] `instance-setup/environment.md` - Environment variables
* \[ ] `instance-setup/email.md` - Email setup
* \[ ] `instance-setup/social-auth.md` - Social auth setup
### API Reference (3/6) 🔄
* \[x] `api/authentication.md` - Authentication endpoints
* \[x] `api/sessions.md` - Session management
* \[x] `api/users.md` - User management
* \[ ] `api/token-auth.md` - Token authentication
* \[ ] `api/social-auth.md` - Social OAuth
* \[ ] `api/admin.md` - Admin operations
### Guides (2/8) 🔄
* \[x] `guides/user-registration.md` - User registration flow
* \[x] `guides/bridge-integration.md` - Bridge integration
* \[ ] `guides/login-flow.md` - Login implementation
* \[ ] `guides/password-reset.md` - Password reset flow
* \[ ] `guides/email-verification.md` - Email verification
* \[ ] `guides/social-login.md` - Social login
* \[ ] `guides/session-management.md` - Session management
* \[ ] `guides/testing.md` - Testing guide
### Security (1/5) 🔄
* \[x] `security/best-practices.md` - Security best practices
* \[ ] `security/authentication.md` - Auth security
* \[ ] `security/sessions.md` - Session security
* \[ ] `security/rate-limiting.md` - Rate limiting
* \[ ] `security/validation.md` - Input validation
### Monitoring (1/4) 🔄
* \[x] `monitoring/dashboard.md` - Dashboard overview
* \[ ] `monitoring/analytics.md` - Analytics and insights
* \[ ] `monitoring/logs.md` - Logs and debugging
* \[ ] `monitoring/alerts.md` - Alerts and notifications
### LLM Documentation (1/2) 🔄
* \[x] `llms.txt` - LLM-friendly summary
* \[ ] `llms-full.txt` - Complete LLM documentation
### Meta Documentation (1/1) ✅
* \[x] `README.md` - Documentation README
***
## 📈 Statistics
### Files Created
* **Total Files**: 17 / 38 (45%)
* **Core Pages**: 5 / 5 (100%)
* **Instance Setup**: 2 / 5 (40%)
* **API Reference**: 3 / 6 (50%)
* **Guides**: 2 / 8 (25%)
* **Security**: 1 / 5 (20%)
* **Monitoring**: 1 / 4 (25%)
### Content Statistics
* **Total Lines**: ~2,500+ lines of documentation
* **Code Examples**: 50+ examples
* **Diagrams**: 8+ Mermaid diagrams
* **API Endpoints**: 15+ documented
***
## 🎯 Next Priority Files
### Week 1 Remaining (High Priority)
1. `instance-setup/environment.md` - Environment variables guide
2. `instance-setup/email.md` - Email configuration
3. `instance-setup/social-auth.md` - OAuth setup
### Week 2 (Medium Priority)
4. `api/token-auth.md` - Token authentication API
5. `api/social-auth.md` - Social OAuth API
6. `api/admin.md` - Admin operations API
7. `guides/login-flow.md` - Login implementation
8. `guides/password-reset.md` - Password reset
### Week 3 (Lower Priority)
9. `guides/email-verification.md` - Email verification
10. `guides/social-login.md` - Social login guide
11. `guides/session-management.md` - Session management
12. `guides/testing.md` - Testing guide
### Week 4 (Security)
13. `security/authentication.md` - Auth security
14. `security/sessions.md` - Session security
15. `security/rate-limiting.md` - Rate limiting
16. `security/validation.md` - Input validation
### Week 5 (Monitoring)
17. `monitoring/analytics.md` - Analytics
18. `monitoring/logs.md` - Logs
19. `monitoring/alerts.md` - Alerts
### Week 6 (Polish)
20. `llms-full.txt` - Complete LLM docs
21. Review and polish all pages
22. Add more examples
23. Test all code snippets
***
## 🚀 How to Run
### Development Server
```bash
cd 2/docs/pubflow-flowless-docs
npm install
npm run dev
```
Visit: `http://localhost:5173`
### Build for Production
```bash
npm run build
npm run preview
```
***
## 📝 Quality Checklist
### Completed ✅
* \[x] Professional landing page
* \[x] Clear navigation structure
* \[x] Consistent styling
* \[x] Code examples in all guides
* \[x] Mermaid diagrams for flows
* \[x] Security warnings where needed
* \[x] Rate limiting documentation
* \[x] Error handling examples
### In Progress 🔄
* \[ ] Complete all API endpoints
* \[ ] All integration guides
* \[ ] All security pages
* \[ ] All monitoring pages
* \[ ] Complete LLM documentation
### Pending ⏳
* \[ ] Test all code examples
* \[ ] Add more real-world examples
* \[ ] Add troubleshooting sections
* \[ ] Add FAQ page
* \[ ] Add changelog
* \[ ] Add migration guides
***
## 🎨 Documentation Standards
### Writing Style
* ✅ Clear, concise language
* ✅ Active voice
* ✅ Second person ("you")
* ✅ Short sentences
* ✅ Code examples for all concepts
### Code Examples
* ✅ TypeScript/JavaScript examples
* ✅ Complete, runnable code
* ✅ Error handling included
* ✅ Comments for clarity
* ✅ Best practices demonstrated
### Visual Elements
* ✅ Mermaid diagrams for flows
* ✅ Tables for structured data
* ✅ Admonitions (tip, warning, danger)
* ✅ Code blocks with syntax highlighting
* ✅ Emoji for visual interest
***
## 🔗 Key Features Documented
### Authentication ✅
* \[x] User registration
* \[x] Login (email/password)
* \[x] Session management
* \[x] Password reset
* \[x] Email verification
* \[ ] Social OAuth (partial)
* \[ ] Token authentication (partial)
### Security ✅
* \[x] Bridge validation
* \[x] Trust tokens
* \[x] Rate limiting
* \[x] Password hashing
* \[x] Session security
* \[x] Best practices
### Integration ✅
* \[x] Bridge API integration
* \[x] Frontend examples (React)
* \[x] Backend examples (Express)
* \[x] Caching strategy
* \[x] Error handling
### Monitoring ✅
* \[x] Dashboard overview
* \[ ] Analytics (pending)
* \[ ] Logs (pending)
* \[ ] Alerts (pending)
***
## 📞 Support
For questions about the documentation:
* **Email**: docs@pubflow.com
* **GitHub**: https://github.com/pubflow/flowless-docs
* **Community**: https://community.pubflow.com
***
**Status**: 🟢 On Track | **Next Milestone**: Complete Week 1 files (3 remaining)
---
---
url: /api/auth-me.md
---
---
---
url: /api/social-providers.md
---
---
---
url: /operations/getSocialProviders.md
---
---
---
url: /operations/blogGetAuthorProfile.md
---
## Notes
* Rate limit: `post` bucket, 10 requests / 3600s by default. A session that can publish (`admin`, `superadmin`, `author`, `editor`, or the roles in `BLOG_ALLOWED_POST_ROLES` and `BLOG_ADMIN_ROLES`) is not counted. Otherwise `429` `RATE_LIMIT_EXCEEDED`. See [Rate limits](/api/blog#rate-limits).
---
---
url: /operations/blogGetPostById.md
---
Read a single blog post by database id.
Auth: optional.
## Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| `id` | path | string | Yes | Post id |
## Request Body
None.
## Response 200
```json
{
"data": { "id": "post_1", "slug": "hello-world", "title": "Hello" },
"user_context": { "authenticated": true },
"meta": {}
}
```
## Response Errors
* `404` post not found
## Notes
* Useful for internal tools and admin workflows.
* Returns the same response shape as the slug lookup.
---
---
url: /operations/blogGetPostBySlug.md
---
Read a single blog post by slug.
Auth: optional.
## Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| `slug` | path | string | Yes | Post slug |
## Request Body
None.
## Response 200
```json
{
"data": { "id": "post_1", "slug": "hello-world", "title": "Hello" },
"user_context": { "authenticated": false },
"meta": {}
}
```
## Response Errors
* `404` post not found
## Notes
* Best for public content pages.
* Slugs should be unique and stable.
* Returns the post payload plus viewer context.
---
---
url: /operations/blogGetReactions.md
---
---
---
url: /operations/getSessionCurrent.md
---
## Behavior Notes
* Full session: success=true with sessionId, user, expiresAt.
* Pending 2FA: success=false with requires\_2fa=true, sessionId, available\_methods, and user.
---
---
url: /operations/getCurrentUser.md
---
## Behavior Notes
* Endpoint path: /auth/user/me
* Strict auth: BOTH X-Bridge-Secret and session (cookie or X-Session-ID).
* /auth/me is legacy (getCurrentUserLegacy); same formatter for user fields.
* User includes business + privacy fields when columns exist; **acquisition\_* and team\_size\_range are never returned*\* (write-only via onboarding complete).
* Privacy-focused read: [Get privacy](/operations/getUserPrivacy).
* Writes: [Complete onboarding](/operations/onboardingComplete), [Update profile](/operations/updateUserProfile) (biz), privacy routes.
---
---
url: /operations/getCurrentUserLegacy.md
---
## Behavior Notes
* Endpoint path: /auth/me
* Auth requirements: session cookie or X-Session-ID (Bridge secret not required).
* Legacy response shape on full session: success + data.user
* Example real full session shape: { success: true, data: { user: { id, email, name, last\_name, user\_name, user\_type, picture, is\_verified, two\_factor, ... } } }
* Pending 2FA shape: success=false with requires\_2fa, sessionId, available\_methods, user
* For login-compatible shape (success, user, sessionId, expiresAt), prefer /auth/user/me
---
---
url: /api/social-accounts.md
---
---
---
url: /operations/getSocialAccounts.md
---
---
---
url: /operations/postTypesGet.md
---
Get one post type definition by `type_key`.
Auth: public.
## Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| `key` | path | string | Yes | `type_key` |
## Request Body
None.
## Response 200
```json
{
"data": {
"type_key": "case-study",
"type_name": "Case Study",
"field_schema": [],
"behaviors": {},
"is_active": true,
"is_built_in": false
}
}
```
## Response Errors
* `404` type not found
* `503` `MODULE_DISABLED`
## Notes
* Use for admin detail views and type-aware editors.
* Prefer `/schema` when you only need editor fields + behaviors.
---
---
url: /operations/postTypesSchema.md
---
Public editor schema for a type: fields, behaviors, icon, slug prefix, color.
Auth: public.
## Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| `key` | path | string | Yes | `type_key` |
## Request Body
None.
## Response 200
```json
{
"data": {
"type_key": "case-study",
"type_name": "Case Study",
"field_schema": [
{
"name": "client",
"label": "Client",
"type": "text",
"required": true
}
],
"behaviors": {
"requires_approval": true,
"enables_seo": true
},
"icon": "briefcase",
"slug_prefix": "case-studies",
"color": "#2563eb"
}
}
```
## Response Errors
* `404` type not found
* `503` `MODULE_DISABLED`
## Notes
* Aggressive cache TTL (~86400s) unless `POST_TYPES_FRESH_CACHE_MODE` is true.
* Use this to drive dynamic forms in Admin / editors.
---
---
url: /operations/postTypesStats.md
---
Admin stats for one type: totals by status, language, and author.
Auth: session + post-types admin role.
## Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| `key` | path | string | Yes | `type_key` |
## Request Body
None.
## Response 200
```json
{
"data": {
"type_key": "case-study",
"total": 12,
"by_status": { "published": 8, "draft": 4 },
"by_lang": { "en": 7, "es": 5 },
"by_author": [{ "author_id": "u_1", "count": 5 }]
}
}
```
## Response Errors
* `401` missing session
* `403` insufficient role
* `404` type not found
* `503` `MODULE_DISABLED`
## Notes
* Useful for type management dashboards and capacity checks (`max_per_author`).
---
---
url: /operations/getUserPrivacy.md
---
Returns GDPR/CCPA/`privacy_region` for the authenticated user.
Path: `GET /auth/user/me/privacy`\
Auth: session. `404 module_not_installed` if ext-privacy columns are missing.
---
---
url: /operations/adminGetUser.md
---
Path: `GET /auth/admin/users/:id`
Includes business + privacy fields when module columns exist. **Never** returns acquisition fields (write-only via onboarding complete).
Related: [Patch user privacy](/operations/adminPatchUserPrivacy) · [List users](/operations/adminListUsers)
---
---
url: /getting-started.md
---
# Getting Started
Get up and running with Flowless in under 5 minutes. This guide will walk you through creating your first Flowless instance and making your first API call.
::: tip 🚀 Want to Skip the Setup?
Use our **production-ready starter kits** with Flowless authentication already integrated!
**Full-Stack Starter Kits:**
* **[Next.js](https://github.com/pubflow/next-flowfull-client)** - Complete web app with auth, routing, and UI
* **[TanStack Start (React)](https://github.com/pubflow/react-flowfull-client)** - React web app with TanStack Start, auth, routing, and UI
* **[React Native Expo](https://github.com/pubflow/create-pubflow-rn)** - Mobile app with secure storage and offline support
Both include Flowless auth + Flowfull backend + beautiful UI - ready to deploy! 🎉
👉 [View All Starter Kits](https://clients.flowfull.dev/starter-kits)
**Don't need to know the API?** Use [**Flowfull Clients**](https://clients.flowfull.dev/) - Pre-built UI components and hooks that handle all the API calls for you! Perfect for developers who want to focus on building features, not authentication. 🎨
:::
***
## Prerequisites
Before you begin, make sure you have:
* A [Pubflow account](https://pubflow.com/signup) (free to create)
* Basic understanding of REST APIs
* A tool to make HTTP requests (cURL, Postman, or your favorite HTTP client)
***
## Step 1: Create a Flowless Instance
1. **Sign up or log in** to [Pubflow.com](https://pubflow.com)
2. **Navigate to the Dashboard**
* Click on "Create New Instance"
* Select "Flowless" as the service type
3. **Configure your instance**
* **Instance Name**: Choose a unique name (e.g., `my-app-auth`)
* **Region**: Select the region closest to your users
* **Plan**: Start with the Free plan (up to 1,000 users)
4. **Create the instance**
* Click "Create Instance"
* Wait 30-60 seconds for provisioning
5. **Get your instance URL**
* Your instance URL will be: `https://your-instance-name.pubflow.com`
* Save this URL - you'll need it for all API calls
***
## Step 2: Make Your First API Call
Let's register a new user using the Flowless API.
### Using cURL
```bash
curl -X POST https://your-instance-name.pubflow.com/auth/register \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com",
"password": "SecurePassword123!",
"name": "John",
"last_name": "Doe"
}'
```
### Using JavaScript (Fetch)
```javascript
const response = await fetch('https://your-instance-name.pubflow.com/auth/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: 'user@example.com',
password: 'SecurePassword123!',
name: 'John',
last_name: 'Doe',
}),
});
const data = await response.json();
console.log(data);
```
### Expected Response
```json
{
"success": true,
"data": {
"user": {
"id": "usr_1234567890",
"email": "user@example.com",
"name": "John",
"last_name": "Doe",
"is_verified": false,
"created_at": "2025-12-07T10:00:00Z"
},
"session": {
"session_id": "ses_abcdefghijk",
"expires_at": "2025-12-14T10:00:00Z"
}
}
}
```
🎉 **Congratulations!** You've successfully created a user and received a session ID.
***
## Step 3: Login a User
Now let's log in with the user we just created.
```bash
curl -X POST https://your-instance-name.pubflow.com/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com",
"password": "SecurePassword123!"
}'
```
### Expected Response
```json
{
"success": true,
"data": {
"user": {
"id": "usr_1234567890",
"email": "user@example.com",
"name": "John",
"last_name": "Doe",
"is_verified": false,
"created_at": "2025-12-07T10:00:00Z"
},
"session": {
"session_id": "ses_abcdefghijk",
"expires_at": "2025-12-14T10:00:00Z"
}
}
}
```
***
## Step 4: Get Current User
Use the session ID to get the current authenticated user.
```bash
curl -X GET https://your-instance-name.pubflow.com/auth/me \
-H "X-Session-ID: ses_xyz123456"
```
### Response
```json
{
"success": true,
"data": {
"id": "usr_1234567890",
"email": "user@example.com",
"name": "John",
"last_name": "Doe",
"is_verified": false,
"created_at": "2025-12-07T10:00:00Z"
}
}
```
***
## Step 5: Configure Your Instance
Now that you have a working instance, let's configure it:
1. **Go to the Pubflow Dashboard**
2. **Select your Flowless instance**
3. **Configure settings:**
* Email provider (ZeptoMail)
* Social OAuth providers (Google, Facebook, etc.)
* Rate limiting rules
* Custom branding
See [Instance Configuration](/instance-setup/configuration) for detailed instructions.
***
## Next Steps
Now that you have a working Flowless instance, here's what to do next:
::: tip 🎨 Build Your Frontend
Connect your UI with [**Flowfull Clients**](https://clients.flowfull.dev/) - Pre-built libraries for React, Next.js, and React Native:
* **React**: `npm install @pubflow/react`
* **React Native**: `npm install @pubflow/react-native`
* **Next.js**: `npm install @pubflow/nextjs`
Or use our [**Starter Kits**](https://clients.flowfull.dev/starter-kits) for a complete full-stack app! 🚀
:::
::: info ⚡ Build Your Backend
Need custom business logic? Build your backend with [**Flowfull**](https://flowfull.dev/) -
A production-ready backend framework that integrates seamlessly with Flowless authentication.
[Get Started with Flowfull →](https://flowfull.dev/getting-started)
:::
::: tip 💳 Need Payments?
Add payment processing to your app with [**Bridge Payments**](https://bridgepayments.dev/) -
Supports Stripe, PayPal, Authorize.net, and more!
[Explore Bridge Payments →](https://bridgepayments.dev/)
:::
### Learn the Basics
* [**Core Concepts**](/core-concepts) - Understand sessions, tokens, and trust validation
* [**Architecture**](/architecture) - Learn how Flowless fits into your app
### Explore the API
* [**Authentication API**](/api/authentication) - All auth endpoints
* [**Session Management**](/api/sessions) - Managing user sessions
* [**User Management**](/api/users) - User profile operations
### Integration Guides
* [**User Registration**](/guides/user-registration) - Complete registration flow
* [**Login Flow**](/guides/login-flow) - Implement login in your app
* [**Bridge Integration**](/guides/bridge-integration) - Connect your backend
***
## Common Issues
### "Instance not found"
* Make sure you're using the correct instance URL
* Check that your instance is active in the Pubflow dashboard
### "Invalid credentials"
* Verify the email and password are correct
* Passwords must be at least 8 characters
### "Rate limit exceeded"
* You've made too many requests too quickly
* Wait a few minutes and try again
* See [Rate Limiting](/security/rate-limiting) for details
***
## Need Help?
* 📚 [Documentation](/) - Browse all docs
* 🤖 [LLM Docs](/llms.txt) - AI-friendly quick reference ([full version](/llms-full.txt))
* 💬 [Discord Community](https://discord.gg/EJfPTT6Vh7) - Get help and share ideas
* 📧 [Support](mailto:support@pubflow.com) - Contact support
* 🐛 [Report Bug](https://github.com/pubflow/flowless/issues) - Report issues
***
## 🌐 Explore the Pubflow Ecosystem
| Service | Description | Link |
|---------|-------------|------|
| **Flowless** | Managed authentication service | [flowless.dev](https://flowless.dev/) |
| **Flowfull** | Backend framework | [flowfull.dev](https://flowfull.dev/) |
| **Flowfull Clients** | Frontend libraries & starter kits | [clients.flowfull.dev](https://clients.flowfull.dev/) |
| **Bridge Payments** | Universal payment backend | [bridgepayments.dev](https://bridgepayments.dev/) |
**💬 Community**: [Discord](https://discord.gg/EJfPTT6Vh7) • **📧 Support**: support@pubflow.com • **🐙 GitHub**: [github.com/pubflow](https://github.com/pubflow)
---
---
url: /security/validation.md
---
# Input Validation
::: warning COMING SOON
This page is under construction. Check back soon for complete documentation.
:::
Deep dive into input validation in Flowless.
## Overview
This page will cover:
* Email validation
* Password validation
* Username validation
* Input sanitization
* XSS prevention
***
## Coming Soon
Comprehensive guide covering:
* Validation rules
* Sanitization techniques
* Error messages
* Client-side vs server-side validation
* Best practices
***
## Next Steps
* [**Best Practices**](/security/best-practices) - Security best practices
* [**User Registration**](/guides/user-registration) - Registration with validation
* [**Authentication API**](/api/authentication) - API validation rules
---
---
url: /instance-setup/configuration.md
---
# Instance Configuration
Configure your Flowless instance settings through the Pubflow dashboard.
***
## Accessing Configuration
1. Log in to [Pubflow.com](https://pubflow.com)
2. Navigate to your Flowless instance
3. Click on **"Settings"** or **"Configuration"**
***
## General Settings
### Instance Information
#### Instance Name
* **Current**: Your instance name
* **URL**: `https://your-instance-name.pubflow.com`
* **Cannot be changed** after creation
#### Region
* **Current**: Your selected region
* **Cannot be changed** after creation
* Affects latency and data residency
#### Plan
* **Current Plan**: Free, Pro, or Enterprise
* **Upgrade/Downgrade**: Available in settings
* **Billing**: Monthly or annual
***
## Authentication Settings
### Session Configuration
#### Session Duration
* **Default**: 7 days
* **Range**: 1 hour to 30 days
* **Recommendation**:
* Web apps: 7 days
* Mobile apps: 30 days
* High-security apps: 1-3 days
```json
{
"session_duration_days": 7
}
```
#### Session Refresh
* **Auto-refresh**: Extend session on activity
* **Refresh window**: Last 24 hours before expiration
* **Enabled by default**: Yes
### Email Verification
#### Verification Mode
* **Required**: Users must verify before login
* **Optional**: Users can login without verification
* **Disabled**: No verification emails sent
```json
{
"email_verification": "required"
}
```
#### Verification Link Expiration
* **Default**: 24 hours
* **Range**: 1 hour to 7 days
### Password Requirements
Configure password strength requirements:
```json
{
"password_min_length": 8,
"password_require_uppercase": true,
"password_require_lowercase": true,
"password_require_numbers": true,
"password_require_special": true
}
```
#### Custom Password Rules
* **Min Length**: 6-32 characters
* **Uppercase**: A-Z required
* **Lowercase**: a-z required
* **Numbers**: 0-9 required
* **Special**: !@#$%^&\* required
***
## Security Settings
### Validation Mode
Choose how strictly sessions are validated:
#### STANDARD (Default)
```bash
VALIDATION_MODE=STANDARD
```
* Validates session ID
* Validates IP address
* **Best for**: Most applications
#### ADVANCED
```bash
VALIDATION_MODE=ADVANCED
```
* Validates session ID
* Validates IP address
* Validates device ID
* **Best for**: Mobile applications
#### STRICT
```bash
VALIDATION_MODE=STRICT
```
* Validates session ID
* Validates IP address
* Validates device ID
* Validates user agent
* **Best for**: High-security applications
### Rate Limiting
Configure rate limits for different endpoints:
```json
{
"rate_limits": {
"login": {
"max_requests": 5,
"window_minutes": 15
},
"register": {
"max_requests": 3,
"window_minutes": 60
},
"password_reset": {
"max_requests": 3,
"window_minutes": 60
},
"api_calls": {
"max_requests": 100,
"window_minutes": 1
}
}
}
```
### IP Whitelisting (Enterprise)
Restrict access to specific IP addresses:
```json
{
"ip_whitelist": [
"192.168.1.0/24",
"10.0.0.0/8"
]
}
```
***
## Email Configuration
See [Email Setup](/instance-setup/email) for detailed email configuration.
### Email Provider
* **Default**: ZeptoMail (included)
* **Custom SMTP**: Enterprise plan only
### Email Templates
* Verification email
* Password reset email
* Welcome email
* Account deletion confirmation
***
## Social Authentication
See [Social Auth Setup](/instance-setup/social-auth) for detailed OAuth configuration.
### Supported Providers
* Google
* Facebook
* GitHub
* Twitter
* LinkedIn
* Custom OAuth 2.0
***
## Advanced Settings
### Database
#### Database Type
* **PostgreSQL** (Recommended)
* **MySQL**
* **LibSQL**
* **SQLite** (Free plan only)
::: warning
Database type cannot be changed after creation. Contact support for migration.
:::
#### Connection Pool
```json
{
"database": {
"max_connections": 20,
"idle_timeout_seconds": 30
}
}
```
### Caching
#### Redis Configuration
```json
{
"cache": {
"enabled": true,
"ttl_seconds": 300,
"max_memory_mb": 256
}
}
```
### Logging
#### Log Level
* **DEBUG**: All logs (development)
* **INFO**: Informational logs (default)
* **WARN**: Warnings and errors
* **ERROR**: Errors only (production)
```json
{
"log_level": "INFO"
}
```
***
## Custom Domain (Pro/Enterprise)
### Setup Custom Domain
1. **Add Domain** in settings
2. **Add DNS Records**:
```
Type: CNAME
Name: auth (or your subdomain)
Value: your-instance.pubflow.com
```
3. **Verify Domain**
4. **Enable SSL** (automatic)
### Example
```
Custom Domain: auth.yourdomain.com
Points to: your-instance.pubflow.com
```
***
## Webhooks (Enterprise)
Configure webhooks for events:
```json
{
"webhooks": [
{
"url": "https://your-backend.com/webhooks/flowless",
"events": ["user.created", "user.login", "user.deleted"],
"secret": "webhook_secret_key"
}
]
}
```
### Available Events
* `user.created`
* `user.login`
* `user.logout`
* `user.verified`
* `user.deleted`
* `user.banned`
* `session.created`
* `session.expired`
* `password.reset`
***
## Environment Variables
Export your configuration as environment variables:
```bash
# Instance
FLOWLESS_URL=https://your-instance.pubflow.com
BRIDGE_SECRET=your_bridge_secret
# Validation
VALIDATION_MODE=STANDARD
# Session
SESSION_DURATION_DAYS=7
# Email
EMAIL_VERIFICATION=required
# Rate Limiting
RATE_LIMIT_LOGIN=5
RATE_LIMIT_REGISTER=3
```
***
## Next Steps
* [**Email Setup**](/instance-setup/email) - Configure email service
* [**Social Auth**](/instance-setup/social-auth) - Set up OAuth providers
* [**Environment Variables**](/instance-setup/environment) - Complete env setup
* [**Monitoring**](/monitoring/dashboard) - Monitor your instance
---
---
url: /operations/invalidateUserCache.md
---
---
---
url: /operations/blogListBookmarks.md
---
List bookmarks for the current user.
Auth: session.
## Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| `page` | query | number | No | Page number |
| `limit` | query | number | No | Items per page |
## Request Body
None.
## Response 200
```json
{
"data": [
{ "post_id": "post_2", "bookmarked_at": "2026-04-02T10:00:00.000Z" }
],
"user_context": { "authenticated": true },
"meta": { "page": 1, "limit": 10, "total": 1 }
}
```
## Response Errors
* `401` missing session
## Notes
* Use this to power saved-items pages.
* Returns only the bookmarks owned by the current user.
---
---
url: /operations/blogListCategories.md
---
List blog categories.
Auth: public.
## Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| `lang` | query | string | No | ISO 639-1 code, such as `es`. Admins and moderators can pass `all`, or omit `lang`, to list every language. A public request with no `lang` or with `all` uses the default language. See [Languages](/api/blog#languages). |
## Request Body
None.
## Response 200
```json
{
"data": [
{ "id": "cat_1", "name": "News", "slug": "news" }
],
"user_context": { "authenticated": false },
"meta": {}
}
```
## Response Errors
* `500` category read error
## Notes
* Used by navigation, filters, and category pages.
* Returns the category list in the standard blog envelope.
---
---
url: /operations/blogListComments.md
---
List comments for a blog post.
Auth: optional.
## Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| `id` | path | string | Yes | Post id |
## Request Body
None.
## Response 200
```json
{
"data": [
{ "id": "com_1", "body": "Great post" }
],
"user_context": { "authenticated": false },
"meta": {}
}
```
## Response Errors
* `404` post not found
## Notes
* Public posts may expose public comments.
* Response shape follows the blog envelope with `data`, `user_context`, and `meta`.
---
---
url: /operations/blogListPosts.md
---
List blog posts with filters and pagination.
Auth: optional.
## Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| `page` | query | number | No | Page number |
| `limit` | query | number | No | Items per page |
| `sort` | query | string | No | Sort field |
| `order` | query | string | No | `asc` or `desc` |
| `q` | query | string | No | Text search |
| `type` | query | string | No | Filter by `post_type` (CPT). Ignored when Post Types is disabled |
| `lang` | query | string | No | ISO 639-1 code, such as `es`. Admins and moderators can pass `all`, or omit `lang`, to list every language. A public request with no `lang` or with `all` uses the default language. See [Languages](/api/blog#languages). |
## Request Body
None.
## Response 200
```json
{
"data": [],
"user_context": { "authenticated": false },
"meta": { "page": 1, "limit": 10, "total": 0, "hasMore": false }
}
```
## Response Errors
* `400` invalid query parameters
## Notes
* Use this for public listing pages.
* Supports page, limit, sort, order, category, tag, author, q, lang, and CPT `type` filters.
* `lang` is an ISO 639-1 code. `lang=all` is only for an admin or moderator session.
* When CPT is enabled, each post may include `post_type` and `custom_fields`.
* Returns the standard `data` / `user_context` / `meta` envelope.
* See also [List Posts by Type](/operations/postTypesPosts).
---
---
url: /operations/blogListTags.md
---
List blog tags.
Auth: public.
## Parameters
| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `lang` | query | string | No | ISO 639-1 code, such as `es`. Omit it, or pass `all`, to list every tag. A specific code returns only tags stored with that code. |
## Request Body
None.
## Response 200
```json
{
"data": [
{ "id": "tag_1", "name": "Release", "slug": "release" }
],
"user_context": { "authenticated": false },
"meta": {}
}
```
## Response Errors
* `500` tag read error
## Notes
* Used by tag search and content filtering.
* Each tag belongs to one language. The same name can exist in another language only when the slug is different.
---
---
url: /operations/blogListTranslations.md
---
List translations for a blog post.
Auth: optional.
## Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| `id` | path | string | Yes | Post id |
## Request Body
None.
## Response 200
```json
{
"data": [
{ "lang": "en", "slug": "hello-world" },
{ "lang": "es", "slug": "hola-mundo" }
],
"user_context": { "authenticated": false },
"meta": {}
}
```
## Response Errors
* `404` post not found
## Notes
* Use this for multilingual content experiences.
* Works best when the base post has a stable source language.
---
---
url: /operations/postTypesList.md
---
List custom post type definitions.
Auth: public.
## Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| `active` | query | string | No | `true` (default) or `false` to include inactive |
## Request Body
None.
## Response 200
```json
{
"data": [
{
"id": "pt_1",
"type_key": "blog",
"type_name": "Blog Post",
"field_schema": [],
"behaviors": { "public_by_default": true },
"is_active": true,
"is_built_in": true,
"sort_order": 0
}
],
"meta": {},
"user_context": { "authenticated": false }
}
```
## Response Errors
* `503` `MODULE_DISABLED` — Post Types off (`POST_TYPES_ENABLED` / MCU)
## Notes
* Default returns active types only.
* Definitions may be Redis-cached unless `POST_TYPES_FRESH_CACHE_MODE` is true.
* Requires Blog + CPT enabled; otherwise `503`.
---
---
url: /operations/postTypesPosts.md
---
List posts for a type. Internal proxy to `GET /api/v1/posts?type={key}` (not a redirect).
Auth: optional (same as blog list posts).
## Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| `key` | path | string | Yes | `type_key` |
| `page` | query | number | No | Page number |
| `limit` | query | number | No | Items per page |
| `lang` | query | string | No | Language filter |
| `status` | query | string | No | Status filter |
| `q` | query | string | No | Text search |
## Request Body
None.
## Response 200
```json
{
"data": [],
"user_context": { "authenticated": false },
"meta": { "page": 1, "limit": 10, "total": 0, "hasMore": false }
}
```
## Response Errors
* `400` invalid query parameters
* `503` `MODULE_DISABLED`
## Notes
* Forwards listing query params to the Blog posts list with `type` set.
* Prefer `GET /api/v1/posts?type=` directly when you already use the Blog client.
---
---
url: /guides/login-flow.md
---
# Login Flow
::: warning COMING SOON
This page is under construction. Check back soon for complete documentation.
:::
Complete guide to implementing user login in your application.
## Overview
This guide will cover:
* Login form implementation
* Email/username authentication
* Password validation
* Session handling
* Error handling
* **Two-Factor Authentication (2FA) flow**
***
## Two-Factor Authentication (Conditional Flow)
When the [**Two-Factor Authentication**](/modules/two-factor) module is active, the login flow behaves differently for users who have 2FA enabled. Complete reference available in the [Two-Factor API](/api/two-factor).
### The Partial Session
If a user successfully authenticates with an email/password (or OAuth) but requires 2FA, the server **will not** return an immediately valid session. Instead, you'll receive a **partial session**:
```json
{
"requires_2fa": true,
"session_id": "ses_xxxxxxxxxxx",
"available_methods": ["email"]
}
```
The emitted `session_id` has a specific `pending` status and a short expiry limit (default 5 minutes). This partial session **can only** be used to access 2FA resolution routes.
### Resolving 2FA (Client-Side)
1. **Store the `session_id`** temporarily in your client as you normally would.
2. **Prompt the user** to enter the 6-digit code sent to their `email` or `sms`.
3. **Submit the code** back to the `/auth/two_factor/verify` endpoint, including the `session_id` cookie or header:
```bash
curl -X POST https://your-instance.pubflow.com/auth/two_factor/verify \
-H "Content-Type: application/json" \
-H "Cookie: session_id=ses_xxxxxxxxxxx" \
-d '{
"code": "123456",
"method": "email",
"action": "login"
}'
```
### Full Session Activation
Once the code is verified successfully, the backend automatically **promotes** the session:
* The session `status` changes from `pending` to `active`.
* `two_factor_verified` becomes `1`.
* The full expiry (e.g., 30 days) is applied.
* A new, fully valid `session_id` cookie is returned in the response.
From this point, the session is indistinguishable from a standard login session and can be verified by your Flowfull backend utilizing the [Bridge Validation Architecture](/architecture).
***
## Coming Soon
Full implementation guide with:
* React login component
* Backend validation
* Session management
* Error handling
* Best practices
***
## Next Steps
* [**User Registration**](/guides/user-registration) - Registration guide
* [**Password Reset**](/guides/password-reset) - Password reset flow
* [**Authentication API**](/api/authentication) - API reference
---
---
url: /operations/loginUser.md
---
## Behavior Notes
* Full session: returns success=true with user, sessionId, expiresAt.
* Pending 2FA: returns success=false with requires\_2fa=true, sessionId, available\_methods, and user.
* Unverified account: when AUTH.verify\_registration=true, returns 403 with code EMAIL\_NOT\_VERIFIED.
Reference:
https://flowless.dev/operations/registerPublic.html
---
---
url: /operations/logoutUser.md
---
---
---
url: /monitoring/logs.md
---
# Logs
::: warning COMING SOON
This page is under construction. Check back soon for complete documentation.
:::
View and search logs for your Flowless instance.
## Overview
This page will cover:
* Authentication logs
* API request logs
* Error logs
* Email logs
* Log search and filtering
***
## Coming Soon
Comprehensive logging guide covering:
* Log types and formats
* Search and filtering
* Log retention
* Export logs
* Real-time log streaming
***
## Next Steps
* [**Dashboard**](/monitoring/dashboard) - Dashboard overview
* [**Analytics**](/monitoring/analytics) - Analytics and insights
* [**Alerts**](/monitoring/alerts) - Configure alerts
---
---
url: /operations/blogModerateComment.md
---
Moderate a blog comment.
Auth: session + moderator/admin.
## Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| `commentId` | path | string | Yes | Comment id |
## Request Body
```json
{
"action": "approve"
}
```
## Response 200
```json
{
"data": { "id": "com_2", "status": "approved" },
"user_context": { "authenticated": true, "user_type": "moderator" },
"meta": {}
}
```
## Response Errors
* `400` invalid moderation action
* `401` missing session
* `403` missing moderator/admin role
* `404` comment not found
* `429` `RATE_LIMIT_EXCEEDED`
## Notes
* Rate limit: `comment` bucket, 30 requests / 3600s by default. Every caller is counted, including publishers. Over the limit returns `429` `RATE_LIMIT_EXCEEDED`. See [Rate limits](/api/blog#rate-limits).
* Use this to approve, reject, or review comments depending on moderation policy.
---
---
url: /api/module-hub.md
---
# Module Hub API
The Module Hub is the operational surface for installing, auditing, and updating modules in Pubflow Platform.
Use it when you need to know what is installed, what changed, and whether a module is ready to run safely.
## How to read this page
Each route is described as a plain operation so the admin workflow is easier to follow.
## What it does
* Discovers module manifests
* Runs dry-run plans before execution
* Installs or updates module components in order
* Tracks registry state and audit events
* Detects drift and checksum changes
* Uses a runtime lock to avoid collisions
## Route map
| Method | Path | Purpose |
|--------|------|---------|
| `GET` | `/api/v1/modules/install/status` | Check whether the hub tables exist |
| `POST` | `/api/v1/modules/install/dry-run` | Simulate hub installation |
| `POST` | `/api/v1/modules/install/run` | Install the hub tables |
| `GET` | `/api/v1/modules/install/` | Discover available modules |
| `GET` | `/api/v1/modules/install/:module_id/status` | Inspect module health and drift |
| `GET` | `/api/v1/modules/install/:module_id/registry` | Read the registry for one module |
| `POST` | `/api/v1/modules/install/:module_id/dry-run` | Plan a module install |
| `POST` | `/api/v1/modules/install/:module_id/run` | Execute a module install |
| `POST` | `/api/v1/modules/install/:module_id/update/dry-run` | Plan targeted updates |
| `POST` | `/api/v1/modules/install/:module_id/update` | Run targeted updates |
## Route details
### Hub status and install
#### `GET /api/v1/modules/install/status`
Check whether the hub tracking tables exist.
Auth: admin/superadmin.
#### `POST /api/v1/modules/install/dry-run`
Simulate creating the hub tables.
Auth: admin/superadmin.
#### `POST /api/v1/modules/install/run`
Create the hub tables.
Auth: admin/superadmin.
### Discovery
#### `GET /api/v1/modules/install/`
Discover available modules by manifest.
Auth: admin/superadmin.
### Module inspection
#### `GET /api/v1/modules/install/:module_id/status`
Inspect installation state, drift, and component health.
Auth: admin/superadmin.
#### `GET /api/v1/modules/install/:module_id/registry`
Read the registry and audit trail for one module.
Auth: admin/superadmin.
### Module execution
#### `POST /api/v1/modules/install/:module_id/dry-run`
Plan a module install before touching the database.
Auth: admin/superadmin.
#### `POST /api/v1/modules/install/:module_id/run`
Execute the module install.
Auth: admin/superadmin.
### Module updates
#### `POST /api/v1/modules/install/:module_id/update/dry-run`
Plan targeted updates for drifted or outdated components.
Auth: admin/superadmin.
#### `POST /api/v1/modules/install/:module_id/update`
Run targeted updates.
Auth: admin/superadmin.
## How to use it
1. Check hub status first.
2. Run a dry-run to see what will happen.
3. Review the plan and component order.
4. Execute the install or update only when the plan looks safe.
5. Inspect the registry and events after the run.
## Example: check hub status
```http
GET /api/v1/modules/install/status
```
Example response:
```json
{
"success": true,
"data": {
"installed": true,
"tables": ["module_hub_registry", "module_hub_events"]
}
}
```
## Example: dry-run a module install
```http
POST /api/v1/modules/install/blog/dry-run
Content-Type: application/json
{
"target": "all",
"runtime_scope": "flowless-core",
"verify_checksum": true
}
```
What you should expect:
* a component-by-component execution plan
* the ordered dependency chain
* whether each item is `install`, `upgrade`, `repair`, `drift`, or `skip`
Example response:
```json
{
"success": true,
"data": {
"module_id": "blog",
"runtime_scope": "flowless-core",
"plan": [
{ "component": "core", "action": "install" },
{ "component": "ext-comments", "action": "install" }
]
}
}
```
## Example: run a module install
```http
POST /api/v1/modules/install/blog/run
Content-Type: application/json
{
"target": "selected",
"components": ["ext-comments", "ext-stats"],
"runtime_scope": "flowless-core",
"skip_existing": true,
"verify_checksum": true
}
```
Useful notes:
* `target: "core"` installs the base module only.
* `target: "selected"` installs specific components and resolves dependencies.
* `target: "all"` installs the full module surface.
## Example: inspect module status
```http
GET /api/v1/modules/install/blog/status
```
Example response:
```json
{
"success": true,
"data": {
"module_id": "blog",
"status": "installed",
"drifted": false,
"components": []
}
}
```
## What to watch for
* Do not run overlapping installs for the same `runtime_scope:module_id`.
* Use dry-runs before updates.
* Prefer targeted updates when only one component family changed.
* Review the registry after every install or repair.
## Next
* [Modules overview](/modules/index)
* [Blog API](/api/blog)
* [Two-Factor Authentication API](/api/two-factor)
---
---
url: /operations/moduleHubDryRun.md
---
---
---
url: /operations/modules/module-hub.md
---
# Module Hub Operations
Individual operation pages for the Module Hub live under `operations/` and are grouped here for easy navigation.
## Routes
* [Module Hub Status](/operations/moduleHubStatus)
* [Module Hub Dry Run](/operations/moduleHubDryRun)
* [Module Hub Run](/operations/moduleHubRun)
* [Discover Modules](/operations/moduleHubDiscover)
* [Module Status](/operations/moduleHubModuleStatus)
* [Module Registry](/operations/moduleHubRegistry)
* [Module Dry Run](/operations/moduleHubModuleDryRun)
* [Module Run](/operations/moduleHubModuleRun)
* [Module Update Dry Run](/operations/moduleHubUpdateDryRun)
* [Module Update](/operations/moduleHubUpdate)
## Response Metadata (New)
Module Hub responses now expose manifest descriptions to improve UI feedback:
* Discover modules (`GET /api/v1/modules/install`) includes `description` and `components_meta[]`.
* Module status (`GET /api/v1/modules/install/{module_id}/status`) includes `module_description` and `components[].description`.
All description fields in the API contract are provided in English.
---
---
url: /operations/moduleHubRun.md
---
---
---
url: /operations/moduleHubStatus.md
---
---
---
url: /operations/moduleHubModuleDryRun.md
---
Plans installation for one module without applying SQL.
Auth: session + admin / superadmin.
## Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| `module_id` | path | string | Yes | e.g. `post-types`, `blog`, `two-factor` |
## Request Body
Optional. Empty body or `{}` uses defaults (`target: "core"`, `runtime_scope: "flowless-core"`).
```json
{
"target": "all",
"runtime_scope": "flowless-core",
"verify_checksum": true,
"repair_missing": false
}
```
| Field | Notes |
|-------|--------|
| `target` | `core` | `selected` | `all`. With `core`, `components` is ignored. |
| `components` | Used only when `target` is `selected`. |
| `runtime_scope` | Default `flowless-core`. |
Always send `Content-Type: application/json` and plain ASCII JSON (no NBSP / smart quotes from rich-text copy-paste).
## Response 200
```json
{
"data": {
"module_id": "post-types",
"runtime_scope": "flowless-core",
"dry_run": true,
"resolved_order": ["core", "ext-seo-per-type", "ext-type-restrictions"]
},
"user_context": { "authenticated": true },
"meta": { "cached": false }
}
```
## Response Errors
| Status | `error` / `code` | Meaning |
|--------|------------------|---------|
| `400` | `Invalid JSON body` / `VALIDATION_ERROR` | Body failed `JSON.parse` before schema checks |
| `400` | `Invalid input` / `VALIDATION_ERROR` | JSON ok; Zod rejected fields (see `fields`) |
| `401` | — | Missing session |
| `403` | — | Admin required |
| `404` | — | Unknown `module_id` |
## Notes
* Dry-run does not write registry rows or apply SQL. Use [Run Module Install](/operations/moduleHubModuleRun) after a good plan.
* For Post Types, prefer `target: "all"` so SEO and restrictions extensions install with core.
* Installing schema does **not** enable CPT — set `POST_TYPES_ENABLED=true` separately.
* See [Post Types API](/api/post-types) and [Post Types module](/modules/post-types).
---
---
url: /operations/moduleHubRegistry.md
---
---
---
url: /operations/moduleHubModuleRun.md
---
---
---
url: /operations/moduleHubModuleStatus.md
---
---
---
url: /operations/moduleHubUpdate.md
---
---
---
url: /operations/moduleHubUpdateDryRun.md
---
---
---
url: /modules.md
---
# Modules
Flowless modules are optional, product-level extensions that keep the core auth experience small while adding focused capabilities on top.
Use this section when you want to understand what a module does, how it fits into the platform, and where to manage it in Pubflow.
## Module Hub
The Module Hub is the operational layer for modules.
In Pubflow Platform, the asset console is the simplest place to install a module, review its current state, and keep updates aligned with the docs.
## At a glance
* Keep the authentication core clean and predictable
* Add features without mixing them into the base auth docs
* Manage installs and updates from the Pubflow Platform asset console
* Document each module with a simple, dev-friendly workflow
## Featured modules
| Module | What it adds | Best for |
|--------|--------------|----------|
| [Module Hub](/operations/modules/module-hub) | Install, inspect, and update modules | Teams that need a clear operational workflow |
| [Blog](/modules/blog) | Posts, categories, comments, publishing workflows | Content-driven products, marketing sites, communities |
| [Post Types](/modules/post-types) | Custom content types, `custom_fields`, per-type behaviors | Case studies, FAQ, KB, and other typed content on top of Blog |
| [Onboarding](/modules/onboarding) | First-run wizard fields on `users` (acquisition, business, privacy) | Growth / consent wizards without new tables |
| [Business](/modules/business) | Business profile on `users` (`ext-business` of Onboarding) | B2B flags, company, country, postal |
| [Privacy](/modules/privacy) | GDPR/CCPA self-service (`ext-privacy` of Onboarding) | Consent banners, opt-out, region selection |
| [2FA](/modules/two-factor) | Login-time verification and stronger account security | Apps that need an extra security layer without rewriting auth |
## Recommended workflow
1. Decide whether the feature belongs in core auth or in a module.
2. Review the module page for the setup and behavior.
3. Install or manage the module from the Pubflow Platform asset console.
4. Keep the docs and runtime configuration aligned.
## Why this section exists
A module should answer three questions quickly:
* What problem does it solve?
* How does it change the product surface?
* How do I manage it safely?
That is the standard used by the module pages in this section.
## Next
* [Modules operations home](/operations/modules/index)
* [Onboarding operations](/operations/modules/onboarding)
* [Business operations](/operations/modules/business)
* [Privacy operations](/operations/modules/privacy)
* [Post Types module](/modules/post-types)
* [Post Types operations](/operations/modules/post-types)
* [Blog operations](/operations/modules/blog)
* [2FA operations](/operations/modules/two-factor)
* [Go back to the home page](/)
---
---
url: /api/modules.md
---
# Modules API Reference
Modules are documented here so the core Flowless auth reference stays focused while product extensions remain easy to discover.
Use this page when you want a quick map of the module surface, the main operational behaviors, and the most relevant live-doc sources.
## Available modules
| Module | What it is | Reference |
|--------|------------|-----------|
| [Module Hub](/operations/modules/module-hub) | Management layer for installing, updating, and auditing modules from Pubflow Platform | Operations index |
| [Blog](/operations/modules/blog) | Modular post/content system with categories, comments, publishing, and extensions | Operations index |
| [Post Types](/operations/modules/post-types) | Custom content types, validated `custom_fields`, and per-type publish behaviors | Operations index + [API overview](/api/post-types) |
| [Onboarding](/operations/modules/onboarding) | First-run complete + biz on `/auth/user/me`; acquisition write-only | Operations index + [API overview](/api/onboarding) |
| [Business](/operations/modules/business) | `is_business` / `biz_*` via `PUT /auth/user/me` (`ext-business`) | Operations index + [API overview](/api/business) |
| [Privacy](/operations/modules/privacy) | GDPR/CCPA/`privacy_region` under `/auth/user/me/privacy*` | Operations index + [API overview](/api/privacy) |
| [2FA](/operations/modules/two-factor) | Login-time security flow with pending sessions, code verification, and session promotion | Operations index |
## How to think about modules
* **Module Hub** is the operational layer.
* **Blog** is a content extension.
* **Post Types** sits on top of Blog for typed content (CPT).
* **Onboarding** adds optional columns on `users` plus `POST /auth/user/me/onboarding/complete`.
* **Business** is the onboarding `ext-business` surface for company profile via `PUT /auth/user/me`.
* **Privacy** is the onboarding `ext-privacy` surface for consent after first run.
* **Two-Factor Authentication** is a security flow that augments login and session handling.
That separation helps developers answer the right question quickly:
* Do I need to manage a module? Use the Module Hub operations index.
* Do I need blog endpoints and content behavior? Read the Blog operations index.
* Do I need custom content types / `custom_fields`? Read the Post Types operations index.
* Do I need first-run acquisition / business fields? Read the Onboarding operations index.
* Do I need business profile updates only? Read the Business operations index.
* Do I need GDPR/CCPA routes? Read the Privacy operations index.
* Do I need stronger login verification? Read the 2FA operations index.
## What you should document for each module
A good module page should always explain:
1. What problem the module solves
2. What routes or behaviors it adds
3. What configuration it depends on
4. How to manage it safely in Pubflow Platform
5. Which page is the implementation reference
## Recommended reading order
* [Modules landing page](/modules/index)
* [Modules operations home](/operations/modules/index)
* [Module Hub operations](/operations/modules/module-hub)
* [Blog operations](/operations/modules/blog)
* [Post Types operations](/operations/modules/post-types)
* [Onboarding operations](/operations/modules/onboarding)
* [Business operations](/operations/modules/business)
* [Privacy operations](/operations/modules/privacy)
* [2FA operations](/operations/modules/two-factor)
* [Blog module](/modules/blog)
* [Post Types module](/modules/post-types)
* [Onboarding module](/modules/onboarding)
* [Business module](/modules/business)
* [Privacy module](/modules/privacy)
* [2FA module](/modules/two-factor)
* [Post Types API](/api/post-types)
* [Onboarding API](/api/onboarding)
* [Business API](/api/business)
* [Privacy API](/api/privacy)
* [Flowless API Reference](/api/authentication)
---
---
url: /operations/modules.md
---
# Modules Operations
This is the operations home for modular features in Flowless docs.
## Choose a module
* [Module Hub operations](/operations/modules/module-hub)
* [Blog operations](/operations/modules/blog)
* [Post Types operations](/operations/modules/post-types)
* [Onboarding operations](/operations/modules/onboarding)
* [Business operations](/operations/modules/business)
* [Privacy operations](/operations/modules/privacy)
* [2FA operations](/operations/modules/two-factor)
---
---
url: /api/social-callback.md
---
---
---
url: /operations/socialCallback.md
---
---
---
url: /api/onboarding.md
---
# Onboarding API
First-run completion and optional acquisition / business / privacy fields on `users`.
Canonical mount: **`/auth/user/me/*`** (not `/api/user`).
Onboarding is the **parent** of [Business](/api/business) (`ext-business`) and [Privacy](/api/privacy) (`ext-privacy`).
## Ownership matrix
| Capability | Path | Notes |
|------------|------|-------|
| Complete wizard + acquisition upsert | `POST /auth/user/me/onboarding/complete` | Sets `first_time=false`; may upsert biz/privacy |
| Update business profile | `PUT /auth/user/me` | `is_business`, `biz_*` incl. `biz_postal_code` — [Business API](/api/business) |
| Privacy GDPR/CCPA/region | `/auth/user/me/privacy*` | [Privacy API](/api/privacy) |
| Read profile (biz + privacy, **no acquisition**) | `GET /auth/user/me` | |
| Read privacy only | `GET /auth/user/me/privacy` | |
Acquisition (`acquisition_*`, `team_size_range`) is **write-only** via complete — never returned on GET.
## Complete (upsert)
```http
POST /auth/user/me/onboarding/complete
Content-Type: application/json
X-Session-ID:
```
Ultra rate limit: **10 / 10 minutes** per IP.
Minimal: `{}` — only sets `first_time=false`.
Full wizard may include acquisition, biz, and privacy fields. Prefer dedicated [privacy routes](/api/privacy) and [business PUT](/api/business) after first run.
## Admin analytics
See [Admin API](/api/admin): acquisition breakdown/funnel, list filters, privacy override.
## Operations
* [Complete onboarding](/operations/onboardingComplete)
* [Get current user](/operations/getCurrentUser)
* [Update user profile](/operations/updateUserProfile)
* [Business API](/api/business)
* [Privacy API](/api/privacy)
* [Onboarding module](/modules/onboarding)
---
---
url: /modules/onboarding.md
---
# Onboarding Module
The Onboarding module stores first-run wizard answers on the `users` row (ALTER TABLE — no new tables): acquisition, team size, business profile, and privacy consent.
Core completion (`first_time = false`) works **without** installing the module. Install the schema when you want those answers persisted and readable.
## Ownership matrix (canonical)
| Concern | Component | Write | Read |
|---------|-----------|-------|------|
| `users.first_time` | Core auth | `POST /auth/user/me/onboarding/complete` | `GET /auth/user/me` |
| `users.title` | Core auth | `PUT /auth/user/me` (or complete) | `GET /auth/user/me` |
| Acquisition + `team_size_range` | `core` / `base.sql` | complete only | **never** on GET |
| Business (`is_business`, `biz_*` incl. `biz_postal_code`) | `ext-business` | `PUT /auth/user/me` or complete | `GET /auth/user/me` |
| Privacy (GDPR/CCPA / `privacy_region`) | `ext-privacy` | `/auth/user/me/privacy*` (complete for first-run only) | GET me + GET privacy |
Related component docs: [Business](/modules/business) · [Privacy](/modules/privacy)
## Friendly rule
1. Optionally install `onboarding` via Module Hub (`target: "all"` recommended).
2. Call `POST /auth/user/me/onboarding/complete` with `{}` or wizard fields (sets `first_time=false`; may upsert acquisition / biz / privacy).
3. Read profile with `GET /auth/user/me` (biz + privacy; no acquisition).
4. Later: [Privacy routes](/modules/privacy) for GDPR/CCPA; [Business](/modules/business) / `PUT /auth/user/me` for company profile.
## Activation / install
```http
POST /api/v1/modules/install/onboarding/run
Content-Type: application/json
```
```json
{
"target": "all",
"runtime_scope": "flowless-core"
}
```
Ultra rate limits: complete 10/10min; privacy writes 20/10min.
## Admin analytics
| Method | Path |
|--------|------|
| `GET` | `/auth/admin/analytics/acquisition` |
| `GET` | `/auth/admin/analytics/acquisition/funnel` |
| `GET` | `/auth/users` with `is_business` / `biz_country` / `privacy_region` |
| `PATCH` | `/auth/admin/users/:id/privacy` |
See [Admin API](/api/admin).
## Read the API docs
* [Onboarding API overview](/api/onboarding)
* [Business API](/api/business)
* [Privacy API](/api/privacy)
* [Onboarding operations](/operations/modules/onboarding)
* [Business operations](/operations/modules/business)
* [Privacy operations](/operations/modules/privacy)
* [Complete onboarding](/operations/onboardingComplete)
* [Get current user](/operations/getCurrentUser)
* [Module Hub dry-run](/operations/moduleHubModuleDryRun)
* [Modules overview](/modules/index)
## Next
* [Business module](/modules/business)
* [Privacy module](/modules/privacy)
* [Post Types module](/modules/post-types)
* [2FA module](/modules/two-factor)
---
---
url: /operations/modules/onboarding.md
---
# Onboarding Operations
Individual operation pages for the Onboarding module (and its extensions) live under `operations/` and are grouped here for easy navigation.
Canonical paths are under **`/auth/user/me/*`**. Acquisition fields are write-only via complete (never returned on GET).
**Related components of this module:** [Business operations](/operations/modules/business) · [Privacy operations](/operations/modules/privacy)
## Ownership matrix
| Concern | Write | Ops |
|---------|-------|-----|
| Complete / acquisition | `POST .../onboarding/complete` | [Complete onboarding](/operations/onboardingComplete) |
| Business `biz_*` | `PUT /auth/user/me` or complete | [Business ops](/operations/modules/business) |
| Privacy GDPR/CCPA | `/auth/user/me/privacy*` | [Privacy ops](/operations/modules/privacy) |
| Read profile | `GET /auth/user/me` | [Get current user](/operations/getCurrentUser) |
## Complete (core)
* [Complete onboarding](/operations/onboardingComplete) — `POST /auth/user/me/onboarding/complete`
## Profile read / write
* [Get current user](/operations/getCurrentUser) — `GET /auth/user/me` (biz + privacy; no acquisition)
* [Get current user (legacy)](/operations/getCurrentUserLegacy) — `GET /auth/me`
* [Update user profile](/operations/updateUserProfile) — `PUT /auth/user/me` (includes `biz_*` when ext-business installed)
## Business (ext-business)
Indexed under [Business operations](/operations/modules/business). Columns written via update profile (preferred) or complete (wizard).
## Privacy (ext-privacy)
* [Get privacy](/operations/getUserPrivacy) — `GET /auth/user/me/privacy`
* [Post GDPR consent](/operations/postGdprConsent) — `POST /auth/user/me/privacy/gdpr-consent`
* [Delete GDPR consent](/operations/deleteGdprConsent) — `DELETE /auth/user/me/privacy/gdpr-consent`
* [Post CCPA opt-out](/operations/postCcpaOptOut) — `POST /auth/user/me/privacy/ccpa-opt-out`
Also indexed under [Privacy operations](/operations/modules/privacy).
## Module Hub
* [Module Install Dry Run](/operations/moduleHubModuleDryRun) — `module_id=onboarding`
* [Run Module Install](/operations/moduleHubModuleRun)
## Admin analytics
* [Acquisition analytics](/operations/adminAcquisitionAnalytics) — `GET /auth/admin/analytics/acquisition`
* [Acquisition funnel](/operations/adminAcquisitionFunnel) — `GET /auth/admin/analytics/acquisition/funnel`
* [List users](/operations/adminListUsers) — `GET /auth/users` (+ `is_business`, `biz_country`, `privacy_region`)
* [Patch user privacy](/operations/adminPatchUserPrivacy) — `PATCH /auth/admin/users/:id/privacy`
* [Get admin user](/operations/adminGetUser) — includes biz + privacy; never acquisition
## Related
* [Onboarding API](/api/onboarding)
* [Business API](/api/business)
* [Privacy API](/api/privacy)
* [Onboarding module](/modules/onboarding)
* [Business module](/modules/business)
* [Privacy module](/modules/privacy)
* [Modules operations home](/operations/modules/index)
---
---
url: /guides/password-reset.md
---
# Password Reset
::: warning COMING SOON
This page is under construction. Check back soon for complete documentation.
:::
Complete guide to implementing password reset functionality.
## Overview
This guide will cover:
* Request password reset
* Email with reset link
* Reset token validation
* New password submission
* Security considerations
***
## Coming Soon
Full implementation guide with:
* Password reset request form
* Email template customization
* Reset page implementation
* Token validation
* Security best practices
***
## Next Steps
* [**Email Setup**](/instance-setup/email) - Configure email service
* [**Users API**](/api/users) - Password reset API
* [**Login Flow**](/guides/login-flow) - Login implementation
---
---
url: /api/auth-login.md
---
---
---
url: /api/auth-logout.md
---
---
---
url: /api/password-reset-complete.md
---
---
---
url: /api/password-reset-request.md
---
---
---
url: /api/auth-register.md
---
---
---
url: /api/post-types.md
---
# Post Types API
The Post Types API manages custom content type definitions (CPT) and pairs with the Blog posts API for typed `custom_fields`.
This page is written to help developers enable CPT safely and call the right routes quickly.
## How to read this page
Each route is also documented as an operation page under [Post Types operations](/operations/modules/post-types):
* what it does
* who can call it
* request shape
* response and error codes
## Base path
All CPT definition routes live under `/api/v1/post-types`.
Related Blog routes live under `/api/v1/posts` (`?type=`, body `post_type` / `custom_fields`).
## Enable first
Installing the Module Hub schema does **not** turn CPT on.
```bash
BLOG_ENABLED=true
POST_TYPES_ENABLED=true
# optional MCU: POST_TYPES_MCU=post-types://enabled
```
If disabled, every `/api/v1/post-types` call returns `503` with `code: MODULE_DISABLED`.
Install schema (after Blog). Prefer dry-run first, then run. Always send `Content-Type: application/json` and plain ASCII JSON (no rich-text / NBSP spaces from copy-paste).
```http
POST /api/v1/modules/install/post-types/dry-run
Content-Type: application/json
X-Session-ID:
```
```json
{
"target": "all",
"runtime_scope": "flowless-core"
}
```
```http
POST /api/v1/modules/install/post-types
Content-Type: application/json
X-Session-ID:
```
```json
{
"target": "all",
"runtime_scope": "flowless-core"
}
```
`target: "all"` installs `core` + `ext-seo-per-type` + `ext-type-restrictions`. `target: "core"` installs only core (ignores `components`). Empty body `{}` is valid and defaults to `target: "core"`.
| Error message | Meaning |
|---------------|---------|
| `Invalid JSON body` | Body failed `JSON.parse` (NBSP/smart quotes, bad Content-Type, truncated JSON) |
| `Invalid input` (+ `fields`) | JSON parsed, but Zod rejected a field |
See [Module Install Dry Run](/operations/moduleHubModuleDryRun).
Sample type definitions are documented on the [Post Types Examples](/modules/post-types#examples) page — Module Hub never auto-installs them.
## What the API is for
* Listing and reading type definitions
* Creating / updating / deleting types (admin)
* Fetching public `field_schema` for admin UIs
* Stats per type (admin)
* Listing posts of a type via proxy
## Route map
| Method | Path | Auth | Purpose |
|--------|------|------|---------|
| `GET` | `/api/v1/post-types` | Public | List types (`?active=false` includes inactive) |
| `POST` | `/api/v1/post-types` | Session + CPT admin | Create a type definition |
| `GET` | `/api/v1/post-types/{key}` | Public | Get one definition |
| `PUT` | `/api/v1/post-types/{key}` | Session + CPT admin | Update definition (`type_key` immutable) |
| `DELETE` | `/api/v1/post-types/{key}` | Session + CPT admin | Delete (not built-in; not if posts exist) |
| `GET` | `/api/v1/post-types/{key}/schema` | Public | Schema for editors (`field_schema`, behaviors, icon…) |
| `GET` | `/api/v1/post-types/{key}/stats` | Session + CPT admin | Counts by status, lang, author |
| `GET` | `/api/v1/post-types/{key}/posts` | Optional | Internal proxy → `GET /api/v1/posts?type={key}` |
### Blog routes used with CPT
| Method | Path | CPT fields |
|--------|------|------------|
| `GET` | `/api/v1/posts` | Query `type` (+ `lang`, filters) |
| `POST` | `/api/v1/posts` | Body `post_type`, `custom_fields` |
| `PUT` | `/api/v1/posts/{id}` | Body `custom_fields` (`post_type` locked) |
See [Blog operations](/operations/modules/blog).
## Example: list types
```http
GET /api/v1/post-types
```
```json
{
"data": [
{
"id": "ptd_1",
"type_key": "case-study",
"type_name": "Case Study",
"field_schema": [],
"behaviors": { "enables_scheduling": true },
"is_active": true,
"is_built_in": false,
"sort_order": 100
}
],
"meta": { "total": 1 }
}
```
## Example: create type
```http
POST /api/v1/post-types
X-Session-ID:
Content-Type: application/json
```
```json
{
"type_key": "case-study",
"type_name": "Case Study",
"description": "Customer success / case study",
"slug_prefix": "case-studies/",
"icon": "briefcase",
"color": "#10B981",
"is_active": true,
"sort_order": 10,
"field_schema": [
{
"name": "client_name",
"label": "Client Name",
"type": "text",
"required": true,
"max_length": 120
},
{
"name": "industry",
"label": "Industry",
"type": "select",
"required": false,
"options": ["Tech", "Finance", "Healthcare", "Retail", "Education", "SaaS", "E-commerce"]
},
{
"name": "challenge",
"label": "The Challenge",
"type": "textarea",
"required": false
},
{
"name": "solution",
"label": "Our Solution",
"type": "textarea",
"required": false
},
{
"name": "results",
"label": "Results Achieved",
"type": "textarea",
"required": true
},
{
"name": "duration",
"label": "Project Duration",
"type": "text",
"required": false
},
{
"name": "project_url",
"label": "Live Project URL",
"type": "url",
"required": false
},
{
"name": "technologies",
"label": "Technologies Used",
"type": "text",
"required": false
}
],
"behaviors": {
"public_by_default": true,
"enables_seo": true,
"enables_comments": false,
"enables_reactions": true,
"enables_bookmarks": true,
"enables_views": true,
"enables_scheduling": true,
"requires_approval": true,
"allows_password_visibility": false,
"default_visibility": "public",
"allowed_body_formats": ["markdown", "html", "tiptap_json"]
}
}
```
Full sample catalog (7 types): [Post Types Examples](/modules/post-types#examples).
## Example: schema for editors
```http
GET /api/v1/post-types/case-study/schema
```
Returns `field_schema`, `behaviors`, `icon`, `slug_prefix`, `color` for dynamic forms.
## field\_schema item shape
```json
{
"name": "client_name",
"label": "Client Name",
"type": "text",
"required": true,
"max_length": 120,
"placeholder": "ACME",
"options": ["Tech", "Finance"]
}
```
Types: `text` | `textarea` | `number` | `url` | `date` | `select` | `multi-select` | `boolean`
## Behaviors (common)
| Key | Effect |
|-----|--------|
| `requires_approval` | Non-admins cannot publish |
| `allows_password_visibility` | Allow `visibility=password` |
| `default_visibility` | Used when visibility omitted on create |
| `enables_scheduling` | Allow `scheduled_at` / schedule |
| `allowed_body_formats` | Restrict `body_format` |
| `max_per_author` | Cap posts of this type per author |
## Error codes
| Code | When |
|------|------|
| `MODULE_DISABLED` | CPT env/MCU off (503) |
| `USER_TYPES_DISABLED` | `POST_TYPES_ALLOW_USER_TYPES=false` |
| `POST_TYPE_LOCKED` | Changing `post_type` after create |
| `APPROVAL_REQUIRED` | Non-admin publish when approval required |
| `MAX_PER_AUTHOR` | Author over type quota |
| `CUSTOM_FIELDS_TOO_LARGE` / validation errors | Bad or oversized `custom_fields` |
## Env reference
| Var | Default | Notes |
|-----|---------|-------|
| `POST_TYPES_ENABLED` | `false` | Master switch |
| `POST_TYPES_MCU` | \`\` | `post-types://enabled@?...` |
| `POST_TYPES_REQUIRE_APPROVAL` | `false` | Global approval |
| `POST_TYPES_DEFAULT_TYPE` | `post` | Default `post_type` |
| `POST_TYPES_ALLOW_USER_TYPES` | `true` | Allow create via API |
| `POST_TYPES_CUSTOM_FIELDS_MAX_KB` | `10` | Cap |
| `POST_TYPES_FIELD_SCHEMA_MAX_KB` | `64` | Cap |
| `POST_TYPES_ADMIN_ROLES` | (blog admin) | Type CRUD + publish under approval |
| `POST_TYPES_CACHE_TTL` | `86400` | Def cache TTL |
| `POST_TYPES_FRESH_CACHE_MODE` | `true` | Bypass Redis when true |
## Operation pages
* [List Post Types](/operations/postTypesList)
* [Create Post Type](/operations/postTypesCreate)
* [Get Post Type](/operations/postTypesGet)
* [Update Post Type](/operations/postTypesUpdate)
* [Delete Post Type](/operations/postTypesDelete)
* [Get Post Type Schema](/operations/postTypesSchema)
* [Get Post Type Stats](/operations/postTypesStats)
* [List Posts by Type](/operations/postTypesPosts)
## Next
* [Post Types module](/modules/post-types)
* [Blog API](/api/blog)
* [Module Hub](/api/module-hub)
---
---
url: /modules/post-types.md
---
# Post Types Module
The Post Types module (CPT) adds typed content on top of the Blog module: a registry of content types, validated `custom_fields`, and per-type behaviors (approval, scheduling, visibility, formats).
This page explains what is core, what is optional, how to activate the feature, and where to read the API.
## Depends on Blog
Install **blog core** first. Post Types extends `posts` with `post_type` and `custom_fields` and adds `post_type_definitions`.
## Core vs Extensions
| Area | Type | Required to use CPT? | Notes |
|------|------|----------------------|-------|
| `post_type_definitions` registry | Core | Yes | Type keys, field schema, behaviors |
| `posts.post_type` + `posts.custom_fields` | Core | Yes | Columns added by module `base.sql` |
| SEO per type (`post_type_seo`) | Extension | No | Schema only in v1 — no dedicated CRUD API |
| Type restrictions (`post_type_restrictions`) | Extension | No | Schema only in v1 — no dedicated CRUD API |
| Sample type catalog | Docs only | No | See [Examples](#examples) — Module Hub never auto-installs sample types |
## Friendly rule
1. Install the module schema via Module Hub.
2. Enable the feature with env (`POST_TYPES_ENABLED` or MCU).
3. Create the types you need via `POST /api/v1/post-types` (use the [Examples](#examples) catalog as a starting point).
**Install ≠ enable.** Schema can exist while the API still returns `503 MODULE_DISABLED` until the flag is on.
## Activation flow
1. Install Blog, then install `post-types` from Module Hub (`target: "all"` installs core + SEO + restrictions extensions).
2. Dry-run (optional) then run — use `Content-Type: application/json` and plain ASCII JSON:
```http
POST /api/v1/modules/install/post-types/dry-run
Content-Type: application/json
```
```json
{
"target": "all",
"runtime_scope": "flowless-core"
}
```
```http
POST /api/v1/modules/install/post-types
Content-Type: application/json
```
```json
{
"target": "all",
"runtime_scope": "flowless-core"
}
```
If you get `400` with `Invalid JSON body`, the request never reached schema validation — usually NBSP/smart quotes from copy-paste, or a missing/wrong `Content-Type`. `Invalid input` with `fields` means the JSON parsed but a field failed validation. See [Module Install Dry Run](/operations/moduleHubModuleDryRun).
3. Set:
```bash
BLOG_ENABLED=true
POST_TYPES_ENABLED=true
# optional: POST_TYPES_MCU=post-types://enabled
```
4. Restart the Flowless instance.
5. Create types, then create posts with `post_type` + `custom_fields` (or filter with `GET /api/v1/posts?type=`).
## Examples
Starter catalog of common content types. Module Hub does **not** install these automatically — create them with `POST /api/v1/post-types` (or copy the JSON below).
### Blog Post (`post`)
* **Slug prefix:** `blog/` · **Icon:** `file-text` · **Color:** `#3B82F6`
* **Fields:** none (`field_schema: []`)
* **Behaviors:** SEO, comments, reactions, bookmarks, views, scheduling on; password visibility allowed; approval off; formats: markdown, html, tiptap\_json
### Case Study (`case-study`)
* **Slug prefix:** `case-studies/` · **Icon:** `briefcase` · **Color:** `#10B981`
* **Fields:** `client_name` (text, required), `industry` (select), `challenge` / `solution` / `results` (textarea; results required), `duration`, `project_url` (url), `technologies`
* **Behaviors:** SEO, reactions, bookmarks, views, scheduling on; **comments off**; **`requires_approval: true`**; password visibility off
### FAQ (`faq`)
* **Slug prefix:** `faq/` · **Icon:** `help-circle` · **Color:** `#F59E0B`
* **Fields:** `answer` (textarea, required)
* **Behaviors:** Lightweight — SEO and engagement flags off; formats: markdown, html
### Knowledge Base (`knowledge-base`)
* **Slug prefix:** `kb/` · **Icon:** `book-open` · **Color:** `#8B5CF6`
* **Fields:** `difficulty` (select), `estimated_time` (number), `product`, `version`
* **Behaviors:** Full engagement + SEO + scheduling; password visibility off
### Team Member (`team-member`)
* **Slug prefix:** `team/` · **Icon:** `users` · **Color:** `#EC4899`
* **Fields:** `job_title` (required), `department`, `bio`, `linkedin` / `twitter` / `github` (url), `join_date` (date), `skills`
* **Behaviors:** No engagement stack; **markdown only**
### Changelog (`changelog`)
* **Slug prefix:** `changelog/` · **Icon:** `list` · **Color:** `#6366F1`
* **Fields:** `version` (required), `change_type` (select, required), `impact` (select)
* **Behaviors:** Reactions + scheduling on; SEO/comments off; markdown only
### Testimonial (`testimonial`)
* **Slug prefix:** `testimonials/` · **Icon:** `message-square` · **Color:** `#14B8A6`
* **Fields:** `author_name` (required), `author_title`, `author_company`, `author_avatar` (url), `rating` (number), `source`
* **Behaviors:** **`requires_approval: true`**; no engagement stack; markdown only
### Create example (`case-study`)
```json
{
"type_key": "case-study",
"type_name": "Case Study",
"description": "Customer success / case study",
"slug_prefix": "case-studies/",
"icon": "briefcase",
"color": "#10B981",
"is_active": true,
"sort_order": 10,
"field_schema": [
{
"name": "client_name",
"label": "Client Name",
"type": "text",
"required": true,
"max_length": 120
},
{
"name": "industry",
"label": "Industry",
"type": "select",
"required": false,
"options": ["Tech", "Finance", "Healthcare", "Retail", "Education", "SaaS", "E-commerce"]
},
{
"name": "challenge",
"label": "The Challenge",
"type": "textarea",
"required": false
},
{
"name": "solution",
"label": "Our Solution",
"type": "textarea",
"required": false
},
{
"name": "results",
"label": "Results Achieved",
"type": "textarea",
"required": true
},
{
"name": "duration",
"label": "Project Duration",
"type": "text",
"required": false
},
{
"name": "project_url",
"label": "Live Project URL",
"type": "url",
"required": false
},
{
"name": "technologies",
"label": "Technologies Used",
"type": "text",
"required": false
}
],
"behaviors": {
"public_by_default": true,
"enables_seo": true,
"enables_comments": false,
"enables_reactions": true,
"enables_bookmarks": true,
"enables_views": true,
"enables_scheduling": true,
"requires_approval": true,
"allows_password_visibility": false,
"default_visibility": "public",
"allowed_body_formats": ["markdown", "html", "tiptap_json"]
}
}
```
Prefer API create for production. Adapt fields and behaviors per product needs.
## Roles and publish approval
| Env | Default | Purpose |
|-----|---------|---------|
| `BLOG_ALLOWED_POST_ROLES` | `admin,superadmin,author,editor` | Create/edit posts |
| `BLOG_ADMIN_ROLES` | `admin,superadmin` | Blog admins |
| `POST_TYPES_ADMIN_ROLES` | inherits blog admins | Manage type definitions + publish when approval is required |
| `POST_TYPES_REQUIRE_APPROVAL` | `false` | Global: force non-admin publishes to draft |
When `POST_TYPES_REQUIRE_APPROVAL` **or** the type’s `behaviors.requires_approval` is true, non-admins cannot publish (`draft` forced / `403 APPROVAL_REQUIRED`). Admins can.
Other common behaviors: password visibility gate, default visibility, scheduling gate, `max_per_author`, `allowed_body_formats`. `post_type` is **locked after create**.
## Read the API docs
* [Post Types operations](/operations/modules/post-types)
* [Post Types API overview](/api/post-types)
* [Blog operations](/operations/modules/blog) (posts with `?type=` and `custom_fields`)
* [Module Hub operations](/operations/modules/module-hub)
* [Blog module](/modules/blog)
## Next
* [Onboarding module](/modules/onboarding)
* [Modules overview](/modules/index)
* [2FA module](/modules/two-factor)
---
---
url: /operations/modules/post-types.md
---
# Post Types Operations
Individual operation pages for the Post Types (CPT) module live under `operations/` and are grouped here for easy navigation.
Requires Blog enabled and `POST_TYPES_ENABLED` (or MCU). Otherwise all routes return `503 MODULE_DISABLED`.
## Definitions
* [List Post Types](/operations/postTypesList)
* [Create Post Type](/operations/postTypesCreate)
* [Get Post Type](/operations/postTypesGet)
* [Update Post Type](/operations/postTypesUpdate)
* [Delete Post Type](/operations/postTypesDelete)
## Schema and stats
* [Get Post Type Schema](/operations/postTypesSchema)
* [Get Post Type Stats](/operations/postTypesStats)
## Posts by type
* [List Posts by Type](/operations/postTypesPosts)
## Related
* [Post Types API overview](/api/post-types)
* [Post Types module](/modules/post-types)
* [Blog operations](/operations/modules/blog)
* [Module Hub operations](/operations/modules/module-hub)
---
---
url: /api/privacy.md
---
# Privacy API
GDPR / CCPA / `privacy_region` self-service on the authenticated user.
Requires Module Hub `onboarding` **ext-privacy** columns. Missing schema → `404`/`400` `module_not_installed`.
## Routes (all under `/auth/user/me`)
| Method | Path | Notes |
|--------|------|-------|
| `GET` | `/auth/user/me/privacy` | Current privacy status |
| `POST` | `/auth/user/me/privacy/gdpr-consent` | Record consent; optional `policy_version`, `privacy_region` |
| `DELETE` | `/auth/user/me/privacy/gdpr-consent` | Withdraw (`gdpr_consent=false`) |
| `POST` | `/auth/user/me/privacy/ccpa-opt-out` | `{ "opt_out": true\|false }` |
Auth: session (`kyselyAuthMiddleware`). Ultra rate limit on writes: **20 / 10 minutes** per IP.
Timestamps (`*_at`) are set server-side only.
First-run wizard may still send privacy fields via [onboarding complete](/api/onboarding); prefer these routes afterward.
**Business updates are not on these routes** — use [Business API](/api/business) / `PUT /auth/user/me`.
## Admin privacy override
`PATCH /auth/admin/users/:id/privacy` — see [Admin API](/api/admin).
## Examples
```http
GET /auth/user/me/privacy
X-Session-ID:
```
```http
POST /auth/user/me/privacy/gdpr-consent
Content-Type: application/json
X-Session-ID:
{ "consent": true, "policy_version": "v2.1", "privacy_region": "eu" }
```
```http
DELETE /auth/user/me/privacy/gdpr-consent
X-Session-ID:
```
```http
POST /auth/user/me/privacy/ccpa-opt-out
Content-Type: application/json
X-Session-ID:
{ "opt_out": true }
```
## Operations
* [Get privacy](/operations/getUserPrivacy)
* [Post GDPR consent](/operations/postGdprConsent)
* [Delete GDPR consent](/operations/deleteGdprConsent)
* [Post CCPA opt-out](/operations/postCcpaOptOut)
* [Onboarding module](/modules/onboarding)
* [Business API](/api/business)
---
---
url: /modules/privacy.md
---
# Privacy Module
Privacy is an **extension** of the [Onboarding](/modules/onboarding) Module Hub package (`ext-privacy.sql`). It ALTERs `users` with GDPR/CCPA consent flags and `privacy_region`.
Install with onboarding `target: "all"` (or the privacy component after core).
**Business profile updates are not here.** Use [Business](/modules/business) / `PUT /auth/user/me` (`ext-business`).
## Friendly rule
1. Install onboarding + ext-privacy via Module Hub.
2. First-run wizard may set privacy via `POST /auth/user/me/onboarding/complete` (Onboarding parent).
3. After that, use dedicated privacy routes under `/auth/user/me/privacy*`.
4. Profile GET (`GET /auth/user/me`) also returns privacy fields when columns exist.
## API
| Method | Path | Notes |
|--------|------|-------|
| `GET` | `/auth/user/me/privacy` | Status |
| `POST` | `/auth/user/me/privacy/gdpr-consent` | Consent + optional `privacy_region` |
| `DELETE` | `/auth/user/me/privacy/gdpr-consent` | Withdraw |
| `POST` | `/auth/user/me/privacy/ccpa-opt-out` | Opt-out |
## Admin privacy override
Admins can override privacy via `PATCH /auth/admin/users/:id/privacy` — see [Admin API](/api/admin) and [adminPatchUserPrivacy](/operations/adminPatchUserPrivacy).
## Docs
* [Privacy API](/api/privacy)
* [Privacy operations](/operations/modules/privacy)
* [Onboarding module](/modules/onboarding) (parent)
* [Business module](/modules/business) (sibling component — not privacy routes)
* [Complete onboarding](/operations/onboardingComplete)
* [Module Hub dry-run](/operations/moduleHubModuleDryRun)
---
---
url: /operations/modules/privacy.md
---
# Privacy Operations
GDPR / CCPA / `privacy_region` self-service for the authenticated user.
All paths under `/auth/user/me/privacy*`. Session auth. Requires onboarding **ext-privacy** schema (`404`/`400 module_not_installed` otherwise). Ultra rate limit on writes: 20 / 10 minutes.
## Status
* [Get privacy](/operations/getUserPrivacy) — `GET /auth/user/me/privacy`
## GDPR
* [Post GDPR consent](/operations/postGdprConsent) — `POST /auth/user/me/privacy/gdpr-consent`
* [Delete GDPR consent](/operations/deleteGdprConsent) — `DELETE /auth/user/me/privacy/gdpr-consent` (withdraw)
## CCPA
* [Post CCPA opt-out](/operations/postCcpaOptOut) — `POST /auth/user/me/privacy/ccpa-opt-out`
## Related
Business profile updates are **not** on privacy routes — see [Business operations](/operations/modules/business).
* [Privacy API overview](/api/privacy)
* [Privacy module](/modules/privacy)
* [Onboarding operations](/operations/modules/onboarding) (parent module)
* [Business operations](/operations/modules/business)
* [Get current user](/operations/getCurrentUser) (privacy fields also on profile GET)
* [Module Hub operations](/operations/modules/module-hub)
## Admin
* [Admin patch user privacy](/operations/adminPatchUserPrivacy) — `PATCH /auth/admin/users/:id/privacy`
* [Admin API](/api/admin)
---
---
url: /operations/blogPublishPost.md
---
Publish a draft blog post.
Auth: session + owner/admin.
## Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| `id` | path | string | Yes | Post id |
## Request Body
Optional.
```json
{}
```
## Response 200
```json
{
"data": { "id": "post_2", "status": "published" },
"user_context": { "authenticated": true },
"meta": {}
}
```
## Response Errors
* `401` missing session
* `403` not owner/admin
* `404` post not found
* `429` `RATE_LIMIT_EXCEEDED`
## Notes
* Rate limit: `post` bucket, 10 requests / 3600s by default. A session that can publish (`admin`, `superadmin`, `author`, `editor`, or the roles in `BLOG_ALLOWED_POST_ROLES` and `BLOG_ADMIN_ROLES`) is not counted. Otherwise `429` `RATE_LIMIT_EXCEEDED`. See [Rate limits](/api/blog#rate-limits).
* Moves a draft to live content.
* Usually called after review or editorial approval.
---
---
url: /security/rate-limiting.md
---
# Rate Limiting
::: warning COMING SOON
This page is under construction. Check back soon for complete documentation.
:::
Deep dive into rate limiting in Flowless.
## Overview
This page will cover:
* Rate limiting rules
* Endpoint-specific limits
* IP-based limiting
* User-based limiting
* Custom rate limits
***
## Coming Soon
Comprehensive guide covering:
* Rate limiting configuration
* Default limits per endpoint
* Custom limit configuration
* Bypass strategies
* Monitoring rate limits
***
## Next Steps
* [**Best Practices**](/security/best-practices) - Security best practices
* [**Dashboard**](/monitoring/dashboard) - Monitor rate limits
* [**Configuration**](/instance-setup/configuration) - Configure limits
---
---
url: /operations/postGdprConsent.md
---
Path: `POST /auth/user/me/privacy/gdpr-consent`\
Body: `{ "consent": boolean, "policy_version"?: string, "privacy_region"?: "eu"|"ca"|"eu_ca"|"global" }`\
Server sets `gdpr_consent_at` when `consent` is true. Ultra rate limit 20/10min.
---
---
url: /operations/registerPublic.md
---
## Behavior Note
This operation is conditional on AUTH.verify\_registration:
* If AUTH.verify\_registration=true, registration does not create a session. The response omits sessionId/expiresAt and the user must verify email first.
* If AUTH.verify\_registration=false, registration creates a session immediately and returns sessionId/expiresAt.
Canonical operation URL:
https://flowless.dev/operations/registerPublic.html
---
---
url: /operations/blogRemoveBookmark.md
---
Remove a bookmark from a blog post.
Auth: session.
## Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| `id` | path | string | Yes | Post id |
## Request Body
None.
## Response 200
```json
{
"data": { "post_id": "post_2", "bookmarked": false },
"user_context": { "authenticated": true },
"meta": {}
}
```
## Response Errors
* `401` missing session
* `404` bookmark not found
* `429` `RATE_LIMIT_EXCEEDED`
## Notes
* Rate limit: `post` bucket, 10 requests / 3600s by default. A session that can publish (`admin`, `superadmin`, `author`, `editor`, or the roles in `BLOG_ALLOWED_POST_ROLES` and `BLOG_ADMIN_ROLES`) is not counted. Otherwise `429` `RATE_LIMIT_EXCEEDED`. See [Rate limits](/api/blog#rate-limits).
* Use this to un-save a post from a reading list.
* Usually paired with the bookmark route in UI toggles.
---
---
url: /operations/requestPasswordReset.md
---
---
---
url: /operations/resendVerification.md
---
---
---
url: /operations/blogRestorePost.md
---
## Notes
* Rate limit: `post` bucket, 10 requests / 3600s by default. A session that can publish (`admin`, `superadmin`, `author`, `editor`, or the roles in `BLOG_ALLOWED_POST_ROLES` and `BLOG_ADMIN_ROLES`) is not counted. Otherwise `429` `RATE_LIMIT_EXCEEDED`. See [Rate limits](/api/blog#rate-limits).
---
---
url: /operations/blogSchedulePost.md
---
Schedule a blog post for later publishing.
Auth: session + owner/admin.
## Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| `id` | path | string | Yes | Post id |
## Request Body
```json
{
"scheduled_at": "2026-04-05T10:00:00.000Z"
}
```
## Response 200
```json
{
"data": { "id": "post_2", "status": "scheduled", "scheduled_at": "2026-04-05T10:00:00.000Z" },
"user_context": { "authenticated": true },
"meta": {}
}
```
## Response Errors
* `400` invalid schedule payload
* `401` missing session
* `403` not owner/admin
* `404` post not found
* `429` `RATE_LIMIT_EXCEEDED`
## Notes
* Rate limit: `post` bucket, 10 requests / 3600s by default. A session that can publish (`admin`, `superadmin`, `author`, `editor`, or the roles in `BLOG_ALLOWED_POST_ROLES` and `BLOG_ADMIN_ROLES`) is not counted. Otherwise `429` `RATE_LIMIT_EXCEEDED`. See [Rate limits](/api/blog#rate-limits).
* Use this for timed editorial publishing.
* The post remains hidden until the scheduled publish moment.
---
---
url: /operations/adminListUsers.md
---
Runtime path: **`GET /auth/users`** (admin / superadmin).
Optional onboarding filters: `is_business`, `biz_country`, `privacy_region` (require module columns; otherwise `module_not_installed`).
Related: [Acquisition analytics](/operations/adminAcquisitionAnalytics) · [Business operations](/operations/modules/business) · [Admin API](/api/admin)
---
---
url: /security/best-practices.md
---
# Security Best Practices
Follow these best practices to ensure your Flowless integration is secure and production-ready.
***
## Bridge Secret Management
### Never Expose Your Bridge Secret
::: danger
**Critical Security Rule**
Never commit your Bridge Secret to version control or expose it in client-side code!
:::
### ✅ DO
```bash
# .env file (add to .gitignore)
BRIDGE_SECRET=bridge_secret_abc123xyz789
```
```typescript
// Backend only
const bridgeSecret = process.env.BRIDGE_SECRET;
```
### ❌ DON'T
```typescript
// NEVER do this!
const bridgeSecret = 'bridge_secret_abc123xyz789'; // Hardcoded
```
```javascript
// NEVER in frontend!
const response = await fetch('/bridge/validate', {
headers: { 'X-Bridge-Secret': 'bridge_secret_abc123xyz789' }
});
```
### Rotate Secrets Regularly
* **Frequency**: Every 90 days minimum
* **After breach**: Immediately
* **When employee leaves**: Within 24 hours
***
## Session Security
### Use HTTPS Only
::: warning
Always use HTTPS in production. Never send session IDs over HTTP.
:::
```typescript
// ✅ Good
const FLOWLESS_URL = 'https://your-instance.pubflow.com';
// ❌ Bad
const FLOWLESS_URL = 'http://your-instance.pubflow.com';
```
### Store Sessions Securely
#### Frontend Storage
```typescript
// ✅ Best: HttpOnly cookies (if possible)
// Set by your backend
res.cookie('session_id', sessionId, {
httpOnly: true,
secure: true,
sameSite: 'strict',
maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days
});
// ✅ Good: localStorage (for SPAs)
localStorage.setItem('session_id', sessionId);
// ❌ Avoid: sessionStorage (lost on tab close)
sessionStorage.setItem('session_id', sessionId);
```
#### Mobile Apps
```typescript
// React Native - Use AsyncStorage
import AsyncStorage from '@react-native-async-storage/async-storage';
await AsyncStorage.setItem('session_id', sessionId);
```
### Clear Sessions on Logout
```typescript
async function logout() {
const sessionId = localStorage.getItem('session_id');
// 1. Call Flowless logout
await fetch(`${FLOWLESS_URL}/auth/logout`, {
method: 'POST',
headers: { 'X-Session-ID': sessionId },
});
// 2. Clear local storage
localStorage.removeItem('session_id');
localStorage.removeItem('user_data');
// 3. Redirect to login
window.location.href = '/login';
}
```
***
## Validation Mode Selection
### Choose the Right Mode
```typescript
// Low-security apps (blogs, public content)
VALIDATION_MODE=STANDARD
// Medium-security apps (e-commerce, SaaS)
VALIDATION_MODE=ADVANCED
// High-security apps (banking, healthcare)
VALIDATION_MODE=STRICT
```
### STANDARD Mode
* ✅ Fast validation
* ✅ Works with dynamic IPs
* ⚠️ Less secure against session hijacking
### ADVANCED Mode
* ✅ Device binding
* ✅ Better mobile security
* ⚠️ Requires device ID management
### STRICT Mode
* ✅ Maximum security
* ✅ Detects browser changes
* ⚠️ May break with browser updates
***
## Password Security
### Enforce Strong Passwords
```json
{
"password_min_length": 12,
"password_require_uppercase": true,
"password_require_lowercase": true,
"password_require_numbers": true,
"password_require_special": true
}
```
### Validate on Frontend
```typescript
function validatePassword(password: string): string[] {
const errors: string[] = [];
if (password.length < 12) {
errors.push('Password must be at least 12 characters');
}
if (!/[A-Z]/.test(password)) {
errors.push('Password must contain uppercase letter');
}
if (!/[a-z]/.test(password)) {
errors.push('Password must contain lowercase letter');
}
if (!/[0-9]/.test(password)) {
errors.push('Password must contain number');
}
if (!/[!@#$%^&*]/.test(password)) {
errors.push('Password must contain special character');
}
return errors;
}
```
### Never Log Passwords
```typescript
// ❌ NEVER do this!
console.log('User password:', password);
logger.info(`Login attempt with password: ${password}`);
// ✅ Log safely
logger.info(`Login attempt for user: ${email}`);
```
***
## Rate Limiting
### Respect Rate Limits
```typescript
async function loginWithRetry(email: string, password: string) {
const response = await fetch(`${FLOWLESS_URL}/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
});
if (response.status === 429) {
const resetTime = response.headers.get('X-RateLimit-Reset');
const waitSeconds = parseInt(resetTime!) - Math.floor(Date.now() / 1000);
throw new Error(`Rate limited. Try again in ${waitSeconds} seconds`);
}
return response.json();
}
```
### Implement Client-Side Rate Limiting
```typescript
class RateLimiter {
private attempts: number[] = [];
canAttempt(maxAttempts: number, windowMs: number): boolean {
const now = Date.now();
this.attempts = this.attempts.filter(time => now - time < windowMs);
if (this.attempts.length >= maxAttempts) {
return false;
}
this.attempts.push(now);
return true;
}
}
const loginLimiter = new RateLimiter();
async function login(email: string, password: string) {
if (!loginLimiter.canAttempt(5, 15 * 60 * 1000)) {
throw new Error('Too many login attempts. Please wait 15 minutes.');
}
// Proceed with login
}
```
***
## Input Validation
### Validate Email Addresses
```typescript
function isValidEmail(email: string): boolean {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
// Always normalize to lowercase
const email = userInput.toLowerCase().trim();
```
### Sanitize User Input
```typescript
function sanitizeInput(input: string): string {
return input
.trim()
.replace(/[<>]/g, '') // Remove HTML tags
.substring(0, 255); // Limit length
}
```
***
## Trust Token Caching
### Cache Securely
```typescript
import { LRUCache } from 'lru-cache';
const trustTokenCache = new LRUCache({
max: 10000,
ttl: 1000 * 60 * 5, // 5 minutes max
});
// ✅ Cache trust tokens
trustTokenCache.set(sessionId, trustToken);
// ✅ Validate before use
const cachedToken = trustTokenCache.get(sessionId);
if (cachedToken && isTokenValid(cachedToken)) {
return decodeToken(cachedToken);
}
```
### Don't Cache Too Long
```typescript
// ❌ Too long - security risk
ttl: 1000 * 60 * 60 // 1 hour
// ✅ Recommended
ttl: 1000 * 60 * 5 // 5 minutes
```
***
## Error Handling
### Don't Leak Information
```typescript
// ❌ Bad - reveals if email exists
if (!user) {
return { error: 'Email not found' };
}
if (!passwordMatch) {
return { error: 'Incorrect password' };
}
// ✅ Good - generic message
if (!user || !passwordMatch) {
return { error: 'Invalid email or password' };
}
```
### Log Security Events
```typescript
// Log failed login attempts
logger.warn('Failed login attempt', {
email,
ip: req.ip,
timestamp: new Date(),
});
// Log successful logins
logger.info('Successful login', {
userId: user.id,
ip: req.ip,
timestamp: new Date(),
});
```
***
## Production Checklist
### Before Going Live
* \[ ] Bridge Secret stored in environment variables
* \[ ] HTTPS enabled on all endpoints
* \[ ] Rate limiting configured
* \[ ] Password requirements enforced
* \[ ] Email verification enabled
* \[ ] Session duration appropriate
* \[ ] Validation mode selected
* \[ ] Error messages don't leak info
* \[ ] Logging configured
* \[ ] Monitoring enabled
* \[ ] Backup plan in place
* \[ ] Security audit completed
***
## Incident Response
### If Bridge Secret is Compromised
1. **Immediately rotate** the secret in Pubflow dashboard
2. **Update** environment variables in all environments
3. **Restart** all backend services
4. **Invalidate** all active sessions
5. **Notify** users to re-login
6. **Investigate** how the breach occurred
7. **Document** the incident
***
## Next Steps
* [**Authentication Security**](/security/authentication) - Auth-specific security
* [**Session Security**](/security/sessions) - Session management security
* [**Rate Limiting**](/security/rate-limiting) - Configure rate limits
* [**Monitoring**](/monitoring/dashboard) - Monitor security events
---
---
url: /guides/session-management.md
---
# Session Management
::: warning COMING SOON
This page is under construction. Check back soon for complete documentation.
:::
Complete guide to managing user sessions in your application.
## Overview
This guide will cover:
* Session creation and storage
* Session validation
* Session refresh
* Session revocation
* Multi-device sessions
***
## Coming Soon
Full implementation guide with:
* Session storage (localStorage, cookies)
* Session validation middleware
* Refresh token handling
* Logout implementation
* Multi-device management
***
## Next Steps
* [**Sessions API**](/api/sessions) - Session API reference
* [**Bridge Integration**](/guides/bridge-integration) - Backend integration
* [**Session Security**](/security/sessions) - Security best practices
---
---
url: /security/sessions.md
---
# Session Security
::: warning COMING SOON
This page is under construction. Check back soon for complete documentation.
:::
Deep dive into session security in Flowless.
## Overview
This page will cover:
* Session token security
* Bridge validation modes
* Trust tokens (PASETO)
* Session hijacking prevention
* Session fixation prevention
***
## Coming Soon
Comprehensive security guide covering:
* Session token generation
* Validation modes (STANDARD, ADVANCED, STRICT)
* Trust token caching
* Attack prevention
* Best practices
***
## Next Steps
* [**Best Practices**](/security/best-practices) - Security best practices
* [**Sessions API**](/api/sessions) - Session API reference
* [**Core Concepts**](/core-concepts) - Session concepts
---
---
url: /api/sessions.md
---
# Sessions API
Manage user sessions, validate sessions, and control active sessions.
***
## Base URL
```
https://your-instance-name.pubflow.com
```
***
## Validate Session (Bridge API)
Validate a session and get a trust token. This endpoint is used by your backend (Flowfull) to validate user sessions.
### Endpoint
```http
POST /bridge/validate
```
### Headers
```http
Content-Type: application/json
X-Bridge-Secret: your_bridge_secret
```
### Request Body
```json
{
"session_id": "ses_xyz123456",
"ip_address": "192.168.1.1",
"user_agent": "Mozilla/5.0...",
"device_id": "device_abc123"
}
```
### Parameters
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `session_id` | string | Yes | Session ID to validate |
| `ip_address` | string | Conditional\* | Client's IP address |
| `user_agent` | string | Conditional\*\* | Client's user agent |
| `device_id` | string | Conditional\*\*\* | Device identifier |
\*Required for STANDARD, ADVANCED, STRICT modes\
\*\*Required for STRICT mode\
\*\*\*Required for ADVANCED, STRICT modes
### Response
```json
{
"success": true,
"data": {
"valid": true,
"trust_token": "v4.public.eyJ1c2VyX2lkIjoidXNyXzEyMzQ1Njc4OTAiLCJzZXNzaW9uX2lkIjoic2VzX3h5ejEyMzQ1NiIsImVtYWlsIjoidXNlckBleGFtcGxlLmNvbSIsIm5hbWUiOiJKb2huIERvZSIsImV4cCI6MTczMzU3NDAwMCwiaWF0IjoxNzMzNTcwNDAwfQ",
"user": {
"id": "usr_1234567890",
"email": "user@example.com",
"name": "John",
"last_name": "Doe",
"username": "johndoe",
"is_verified": true
},
"session": {
"id": "ses_xyz123456",
"expires_at": "2025-12-14T10:00:00Z",
"created_at": "2025-12-07T10:00:00Z"
}
}
}
```
### Trust Token Contents
The trust token is a PASETO token containing:
```json
{
"user_id": "usr_1234567890",
"session_id": "ses_xyz123456",
"email": "user@example.com",
"name": "John Doe",
"exp": 1733574000,
"iat": 1733570400
}
```
### Error Responses
```json
// Invalid session
{
"success": false,
"error": "Invalid or expired session"
}
// IP mismatch (STANDARD/ADVANCED/STRICT)
{
"success": false,
"error": "IP address mismatch"
}
// Device mismatch (ADVANCED/STRICT)
{
"success": false,
"error": "Device ID mismatch"
}
// User agent mismatch (STRICT)
{
"success": false,
"error": "User agent mismatch"
}
// Invalid bridge secret
{
"success": false,
"error": "Unauthorized"
}
```
### Example (Backend)
```typescript
// In your Flowfull backend
async function validateSession(sessionId: string, req: Request) {
const response = await fetch('https://your-instance.pubflow.com/bridge/validate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Bridge-Secret': process.env.BRIDGE_SECRET!,
},
body: JSON.stringify({
session_id: sessionId,
ip_address: req.headers.get('x-forwarded-for') || req.ip,
user_agent: req.headers.get('user-agent'),
device_id: req.headers.get('x-device-id'),
}),
});
const data = await response.json();
if (!data.success || !data.data.valid) {
throw new Error('Invalid session');
}
// Cache the trust token for 5 minutes
await cache.set(`trust_token:${sessionId}`, data.data.trust_token, 300);
return data.data.user;
}
```
***
## Get User Sessions
Get all active sessions for the authenticated user.
### Endpoint
```http
GET /auth/sessions
```
### Headers
```http
X-Session-ID: ses_xyz123456
```
### Response
```json
{
"success": true,
"data": [
{
"id": "ses_xyz123456",
"device_id": "device_abc123",
"ip_address": "192.168.1.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)...",
"created_at": "2025-12-07T10:00:00Z",
"expires_at": "2025-12-14T10:00:00Z",
"is_current": true
},
{
"id": "ses_def456789",
"device_id": "device_xyz789",
"ip_address": "192.168.1.2",
"user_agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0...)...",
"created_at": "2025-12-06T15:30:00Z",
"expires_at": "2025-12-13T15:30:00Z",
"is_current": false
}
]
}
```
***
## Revoke Session
Revoke a specific session (logout from a specific device).
### Endpoint
```http
DELETE /auth/sessions/:session_id
```
### Headers
```http
X-Session-ID: ses_xyz123456
```
### Parameters
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `session_id` | string | Yes | Session ID to revoke (in URL) |
### Response
```json
{
"success": true,
"message": "Session revoked successfully"
}
```
### Example
```javascript
// Revoke a specific session
await fetch('https://your-instance.pubflow.com/auth/sessions/ses_def456789', {
method: 'DELETE',
headers: {
'X-Session-ID': 'ses_xyz123456', // Current session
},
});
```
***
## Revoke All Sessions
Revoke all sessions except the current one (logout from all other devices).
### Endpoint
```http
DELETE /auth/sessions
```
### Headers
```http
X-Session-ID: ses_xyz123456
```
### Response
```json
{
"success": true,
"message": "All other sessions revoked",
"data": {
"revoked_count": 3
}
}
```
***
## Validation Modes
Flowless supports three validation modes configured via environment variable:
### STANDARD (Default)
Validates:
* ✅ Session ID
* ✅ IP address
```bash
VALIDATION_MODE=STANDARD
```
### ADVANCED
Validates:
* ✅ Session ID
* ✅ IP address
* ✅ Device ID
```bash
VALIDATION_MODE=ADVANCED
```
### STRICT
Validates:
* ✅ Session ID
* ✅ IP address
* ✅ Device ID
* ✅ User agent
```bash
VALIDATION_MODE=STRICT
```
::: tip
Use STANDARD for most applications. Use ADVANCED or STRICT for high-security applications.
:::
***
## Session Security
### Session ID Format
* **Unhashed**: `ses_` prefix (e.g., `ses_xyz123456`)
* **Hashed**: `hashed_ses_` prefix (stored in database)
* **Algorithm**: SHA-256
### Session Expiration
* **Default**: 7 days
* **Configurable**: 1 hour to 30 days
* **Auto-cleanup**: Expired sessions are automatically deleted
### Session Binding
Sessions can be bound to:
* **IP Address**: Prevents session hijacking from different IPs
* **Device ID**: Prevents session use on different devices
* **User Agent**: Prevents session use from different browsers/apps
***
## Next Steps
* [**Authentication API**](/api/authentication) - Login and registration
* [**Users API**](/api/users) - User management
* [**Security Best Practices**](/security/best-practices) - Secure your sessions
---
---
url: /api/social-auth.md
---
# Social Authentication API
::: warning COMING SOON
This page is under construction. Check back soon for complete documentation.
:::
Social authentication API endpoints for OAuth 2.0 integration with Google, Facebook, GitHub, and more.
## Overview
Social authentication allows users to:
* Sign up with social accounts
* Link multiple social accounts
* Unlink social accounts
* Get social profile data
***
## Coming Soon
This documentation will cover:
* OAuth initiation endpoints
* Callback handling
* Account linking API
* Social profile retrieval
* Provider-specific configurations
***
## Next Steps
* [**Social Auth Setup**](/instance-setup/social-auth) - Configure OAuth providers
* [**Social Login Guide**](/guides/social-login) - Implementation guide
* [**Authentication**](/api/authentication) - Standard authentication
---
---
url: /instance-setup/social-auth.md
---
# Social Authentication Setup
Configure OAuth 2.0 social authentication providers for your Flowless instance to enable login with Google, Facebook, GitHub, and more.
***
## Overview
Flowless supports social authentication (OAuth 2.0) with popular providers:
* ✅ Google
* ✅ Facebook
* ✅ GitHub
* ✅ Twitter
* ✅ LinkedIn
* ✅ Custom OAuth 2.0 providers
***
## Benefits of Social Auth
* **Faster Registration**: Users can sign up in one click
* **Better Security**: No password to remember or manage
* **Higher Conversion**: Reduces friction in signup process
* **Verified Emails**: Social providers verify email addresses
* **Profile Data**: Get user's name, picture, and email automatically
***
## Flowless Environment Configuration
### Required variables
```env
API_BASE_URL=https://your-api.com # Used to build OAuth callback URLs
FRONTEND_URL=https://your-frontend.com # Used for post-login redirects
SOCIAL_LOGIN=true # Global social login feature switch
```
### `callback_mode` — Secure Token Transport
Controls how the session token is delivered after a web OAuth callback. Configure via `SOCIAL_AUTH_MCU` or the `SOCIAL_AUTH` JSON variable.
| Mode | Description | `sessionId` in URL? | Recommended |
|------|-------------|---------------------|-------------|
| `cookie` **(default)** | Full session delivered via HTTP-only cookie. Frontend calls `GET /auth/session/current`. | ❌ No (full session) | ✅ Yes |
| `params` (legacy) | `?session_id=xxx` appended to redirect URL. | ✅ Always | ⚠️ Legacy only |
> **⚠️ Important — 2FA exception:** Even when `callback_mode=cookie` is configured, social login with **two-factor authentication** always includes the partial `session_id` in the redirect URL:
>
> ```
> /login?social_login=success&requires_2fa=true&session_id=ses_partial_xyz&provider=google
> ```
>
> This is required because Safari's Intelligent Tracking Prevention (ITP) and other privacy-focused browsers block cookies set during cross-origin OAuth redirect chains (Google → API → Frontend). Relying on the cookie alone for the 2FA step would cause the OTP form to never appear in these browsers.
>
> **This is safe:** the partial session expires in **5 minutes** and still requires a valid OTP code to become a full session. The frontend removes `session_id` from the browser URL history immediately after consuming it.
```env
# MCU format (recommended)
SOCIAL_AUTH_MCU=social://enabled@config/v1?callback_mode=cookie&providers=google&...
# JSON format
SOCIAL_AUTH='{"enabled":true,"callback_mode":"cookie","providers":{...}}'
```
> **Note**: `callback_mode=cookie` is the default. You only need to set it explicitly if you want legacy `params` behavior.
***
## General Setup Process
For each provider, you'll need to:
1. Create an app in the provider's developer console
2. Get Client ID and Client Secret
3. Configure redirect URI to `${API_BASE_URL}/auth/social/{provider}/callback`
4. Add credentials to Flowless via `SOCIAL_AUTH_MCU` or `SOCIAL_AUTH`
5. Enable the provider
***
## Google OAuth Setup
### Step 1: Create Google OAuth App
1. Go to [Google Cloud Console](https://console.cloud.google.com)
2. Create a new project or select existing
3. Navigate to **APIs & Services** → **Credentials**
4. Click **Create Credentials** → **OAuth 2.0 Client ID**
5. Select **Web application**
### Step 2: Configure OAuth Consent Screen
1. Go to **OAuth consent screen**
2. Select **External** user type
3. Fill in app information:
* **App name**: Your app name
* **User support email**: Your email
* **Developer contact**: Your email
4. Add scopes:
* `userinfo.email`
* `userinfo.profile`
5. Save and continue
### Step 3: Get Credentials
1. Go back to **Credentials**
2. Create **OAuth 2.0 Client ID**
3. Add authorized redirect URIs:
```
https://your-instance.pubflow.com/auth/social/google/callback
```
4. Copy **Client ID** and **Client Secret**
### Step 4: Add to Flowless
1. Go to Pubflow Dashboard → Your Instance → **Settings** → **Social Auth**
2. Enable **Google**
3. Enter:
* **Client ID**: Your Google Client ID
* **Client Secret**: Your Google Client Secret
4. Save
***
## Facebook OAuth Setup
### Step 1: Create Facebook App
1. Go to [Facebook Developers](https://developers.facebook.com)
2. Click **My Apps** → **Create App**
3. Select **Consumer** app type
4. Fill in app details
### Step 2: Configure Facebook Login
1. Add **Facebook Login** product
2. Go to **Settings** → **Basic**
3. Add **App Domains**: `your-instance.pubflow.com`
4. Copy **App ID** and **App Secret**
### Step 3: Configure OAuth Redirect
1. Go to **Facebook Login** → **Settings**
2. Add **Valid OAuth Redirect URIs**:
```
https://your-instance.pubflow.com/auth/social/facebook/callback
```
3. Save changes
### Step 4: Add to Flowless
1. Go to Pubflow Dashboard → **Social Auth**
2. Enable **Facebook**
3. Enter:
* **App ID**: Your Facebook App ID
* **App Secret**: Your Facebook App Secret
4. Save
***
## GitHub OAuth Setup
### Step 1: Create GitHub OAuth App
1. Go to [GitHub Settings](https://github.com/settings/developers)
2. Click **OAuth Apps** → **New OAuth App**
3. Fill in:
* **Application name**: Your app name
* **Homepage URL**: `https://yourdomain.com`
* **Authorization callback URL**:
```
https://your-instance.pubflow.com/auth/social/github/callback
```
4. Click **Register application**
### Step 2: Get Credentials
1. Copy **Client ID**
2. Generate **Client Secret**
3. Copy **Client Secret**
### Step 3: Add to Flowless
1. Go to Pubflow Dashboard → **Social Auth**
2. Enable **GitHub**
3. Enter:
* **Client ID**: Your GitHub Client ID
* **Client Secret**: Your GitHub Client Secret
4. Save
***
## Twitter OAuth Setup
### Step 1: Create Twitter App
1. Go to [Twitter Developer Portal](https://developer.twitter.com/en/portal/dashboard)
2. Create a new project and app
3. Go to **App Settings** → **User authentication settings**
4. Enable **OAuth 2.0**
### Step 2: Configure OAuth
1. Set **Type of App**: Web App
2. Add **Callback URI**:
```
https://your-instance.pubflow.com/auth/social/twitter/callback
```
3. Add **Website URL**: `https://yourdomain.com`
4. Copy **Client ID** and **Client Secret**
### Step 3: Add to Flowless
1. Go to Pubflow Dashboard → **Social Auth**
2. Enable **Twitter**
3. Enter:
* **Client ID**: Your Twitter Client ID
* **Client Secret**: Your Twitter Client Secret
4. Save
***
## LinkedIn OAuth Setup
### Step 1: Create LinkedIn App
1. Go to [LinkedIn Developers](https://www.linkedin.com/developers/apps)
2. Click **Create app**
3. Fill in app details
4. Verify your app
### Step 2: Configure OAuth
1. Go to **Auth** tab
2. Add **Redirect URLs**:
```
https://your-instance.pubflow.com/auth/social/linkedin/callback
```
3. Request **Sign In with LinkedIn** product
4. Copy **Client ID** and **Client Secret**
### Step 3: Add to Flowless
1. Go to Pubflow Dashboard → **Social Auth**
2. Enable **LinkedIn**
3. Enter:
* **Client ID**: Your LinkedIn Client ID
* **Client Secret**: Your LinkedIn Client Secret
4. Save
***
## Custom OAuth Provider
### Step 1: Configure Custom Provider
1. Go to Pubflow Dashboard → **Social Auth** → **Custom Provider**
2. Click **Add Custom Provider**
3. Fill in:
* **Provider Name**: e.g., "MyProvider"
* **Authorization URL**: `https://provider.com/oauth/authorize`
* **Token URL**: `https://provider.com/oauth/token`
* **User Info URL**: `https://provider.com/oauth/userinfo`
* **Client ID**: Your client ID
* **Client Secret**: Your client secret
* **Scopes**: `email profile`
### Step 2: Configure Redirect URI
Add this redirect URI to your OAuth provider:
```
https://your-instance.pubflow.com/auth/social/custom/callback
```
***
## Testing Social Auth
### Test Login Flow
1. Go to your app's login page
2. Click "Login with Google" (or other provider)
3. Authorize the app
4. Verify you're logged in
5. Check user data is correct
### Test via API
```bash
# Initiate OAuth flow
curl https://your-instance.pubflow.com/auth/social/google
# This will redirect to Google's OAuth page
# After authorization, user is redirected back with session_id
```
***
## Frontend Implementation
### React Example
```typescript
function SocialLogin() {
const handleGoogleLogin = () => {
window.location.href = `${FLOWLESS_URL}/auth/social/google`;
};
const handleFacebookLogin = () => {
window.location.href = `${FLOWLESS_URL}/auth/social/facebook`;
};
const handleGitHubLogin = () => {
window.location.href = `${FLOWLESS_URL}/auth/social/github`;
};
return (
Login with Google
Login with Facebook
Login with GitHub
);
}
```
### Handling Callback
**Cookie mode (default, recommended) — full session (no 2FA)**
After OAuth completes with no 2FA required, Flowless redirects without exposing the session token in the URL:
```
https://yourdomain.com/login?social_login=success&provider=google
```
Your frontend calls `GET /auth/session/current` (with `credentials: 'include'`) to resolve the session:
```typescript
useEffect(() => {
const params = new URLSearchParams(window.location.search);
if (params.get('social_login') !== 'success') return;
if (params.get('session_id')) return; // 2FA case — handled separately
fetch(`${FLOWLESS_URL}/auth/session/current`, { credentials: 'include' })
.then(r => r.json())
.then(data => {
if (data.success && data.user) {
localStorage.setItem('pubflow_session_id', data.sessionId);
window.location.href = '/dashboard';
}
});
}, []);
```
**Cookie mode (default, recommended) — 2FA pending**
When the authenticated user has 2FA enabled, the redirect **always includes `session_id` in the URL**, even with `callback_mode=cookie`. This is required to bypass Safari ITP cookie blocking:
```
https://yourdomain.com/login?social_login=success&requires_2fa=true&session_id=ses_partial_xyz&provider=google
```
Your frontend reads `session_id` from the URL, shows the OTP form, and should clean the param from browser history after consuming it:
```typescript
// Clean session_id from URL history after consuming it
const clean = new URL(window.location.href);
clean.searchParams.delete('session_id');
window.history.replaceState(null, '', clean.toString());
```
**Params mode (legacy only)**
Only use this if your frontend cannot call `/auth/session/current`. Set `callback_mode=params` in your config. The full session token will appear in the redirect URL:
```
https://yourdomain.com/login?social_login=success&provider=google&session_id=ses_xyz123
```
> ⚠️ **Security note**: Params mode exposes the full session token in browser history, server logs, and Referer headers. Prefer cookie mode for all new deployments.
***
## Account Linking
### Link Social Account
Users can link multiple social accounts to one Flowless account:
```bash
POST /auth/social/link
Headers: X-Session-ID: ses_xyz123
Body: {
"provider": "google",
"access_token": "google_access_token"
}
```
### Unlink Social Account
```bash
DELETE /auth/social/unlink/google
Headers: X-Session-ID: ses_xyz123
```
***
## Security Considerations
### State Parameter
Flowless automatically includes a `state` parameter to prevent CSRF attacks.
### Scope Limitations
Only request necessary scopes:
* ✅ `email`, `profile` - Essential
* ❌ `contacts`, `calendar` - Unnecessary
### Token Storage
* Social access tokens are stored securely
* Refresh tokens are encrypted
* Tokens are never exposed to frontend
***
## Troubleshooting
### "Redirect URI mismatch"
* Verify redirect URI in provider console matches exactly:
```
https://your-instance.pubflow.com/auth/social/{provider}/callback
```
### "Invalid client ID"
* Double-check Client ID and Client Secret
* Ensure no extra spaces
* Regenerate credentials if needed
### "App not verified"
* Some providers require app verification for production
* Submit app for review in provider console
***
## Next Steps
* [**Social Login Guide**](/guides/social-login) - Implement social login
* [**User Registration**](/guides/user-registration) - User registration flow
* [**API Reference**](/api/social-auth) - Social auth API endpoints
---
---
url: /guides/social-login.md
---
# Social Login
::: warning COMING SOON
This page is under construction. Check back soon for complete documentation.
:::
Complete guide to implementing social login with Google, Facebook, GitHub, and more.
## Overview
This guide will cover:
* OAuth 2.0 flow
* Social login buttons
* Callback handling
* Account linking
* Error handling
***
## Coming Soon
Full implementation guide with:
* Social login buttons (React)
* OAuth flow implementation
* Callback page
* Account linking
* Provider-specific guides
***
## Next Steps
* [**Social Auth Setup**](/instance-setup/social-auth) - Configure OAuth providers
* [**Social Auth API**](/api/social-auth) - API reference
* [**User Registration**](/guides/user-registration) - Registration guide
---
---
url: /operations/twoFactorStart.md
---
---
---
url: /operations/twoFactorEmailSetup.md
---
---
---
url: /api/social-login.md
---
---
---
url: /operations/socialLogin.md
---
---
---
url: /operations/twoFactorSmsSetup.md
---
---
---
url: /guides/testing.md
---
# Testing
::: warning COMING SOON
This page is under construction. Check back soon for complete documentation.
:::
Complete guide to testing your Flowless integration.
## Overview
This guide will cover:
* Unit testing authentication
* Integration testing
* E2E testing
* Mocking Flowless API
* Test environments
***
## Coming Soon
Full testing guide with:
* Jest/Vitest examples
* Mock implementations
* Test fixtures
* CI/CD integration
* Best practices
***
## Next Steps
* [**Getting Started**](/getting-started) - Quick start guide
* [**Bridge Integration**](/guides/bridge-integration) - Backend integration
* [**Environment Variables**](/instance-setup/environment) - Test environment setup
---
---
url: /operations/twoFactorToggle.md
---
---
---
url: /api/token-auth.md
---
# Token Authentication
::: warning COMING SOON
This page is under construction. Check back soon for complete documentation.
:::
Token-based authentication allows you to authenticate users using secure tokens instead of traditional session cookies.
## Overview
Token authentication is useful for:
* Mobile applications
* Single-page applications (SPAs)
* API-only integrations
* Microservices
***
## Coming Soon
This documentation will cover:
* Creating authentication tokens
* Validating tokens
* Refreshing tokens
* Revoking tokens
* Token security best practices
***
## Next Steps
* [**Authentication**](/api/authentication) - Standard authentication
* [**Sessions**](/api/sessions) - Session management
* [**Users**](/api/users) - User management
---
---
url: /operations/blogTrackView.md
---
Track a blog post view.
Auth: public.
## Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| `id` | path | string | Yes | Post id |
## Request Body
Optional.
```json
{}
```
## Response 200
```json
{
"data": { "post_id": "post_2", "tracked": true },
"user_context": { "authenticated": false },
"meta": {}
}
```
## Response Errors
* `404` post not found
* `429` `RATE_LIMIT_EXCEEDED`
## Notes
* Rate limit: `view` bucket, 200 requests / 3600s by default. Every caller is counted. Over the limit returns `429` `RATE_LIMIT_EXCEEDED`. See [Rate limits](/api/blog#rate-limits).
* Use this for engagement analytics.
* The backend should protect against duplicate or abusive counts.
---
---
url: /api/social-unlink.md
---
---
---
url: /operations/unlinkSocialAccount.md
---
---
---
url: /operations/blogUnpublishPost.md
---
Return a published blog post to draft.
Auth: session + owner/admin.
## Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| `id` | path | string | Yes | Post id |
## Request Body
Optional.
```json
{}
```
## Response 200
```json
{
"data": { "id": "post_2", "status": "draft" },
"user_context": { "authenticated": true },
"meta": {}
}
```
## Response Errors
* `401` missing session
* `403` not owner/admin
* `404` post not found
* `429` `RATE_LIMIT_EXCEEDED`
## Notes
* Rate limit: `post` bucket, 10 requests / 3600s by default. A session that can publish (`admin`, `superadmin`, `author`, `editor`, or the roles in `BLOG_ALLOWED_POST_ROLES` and `BLOG_ADMIN_ROLES`) is not counted. Otherwise `429` `RATE_LIMIT_EXCEEDED`. See [Rate limits](/api/blog#rate-limits).
* Use this to pull content back from public view.
* Keeps the post editable without deleting it.
---
---
url: /operations/blogUpdateCategory.md
---
## Notes
* Rate limit: `post` bucket, 10 requests / 3600s by default. A session that can publish (`admin`, `superadmin`, `author`, `editor`, or the roles in `BLOG_ALLOWED_POST_ROLES` and `BLOG_ADMIN_ROLES`) is not counted. Otherwise `429` `RATE_LIMIT_EXCEEDED`. See [Rate limits](/api/blog#rate-limits).
---
---
url: /operations/blogUpdateComment.md
---
Update a blog comment.
Auth: session.
## Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| `id` | path | string | Yes | Post id |
| `commentId` | path | string | Yes | Comment id |
## Request Body
```json
{
"body": "Edited comment"
}
```
## Response 200
```json
{
"data": { "id": "com_2", "updated": true },
"user_context": { "authenticated": true },
"meta": {}
}
```
## Response Errors
* `400` invalid comment payload
* `401` missing session
* `403` not allowed
* `404` comment not found
* `429` `RATE_LIMIT_EXCEEDED`
## Notes
* Rate limit: `comment` bucket, 30 requests / 3600s by default. Every caller is counted, including publishers. Over the limit returns `429` `RATE_LIMIT_EXCEEDED`. See [Rate limits](/api/blog#rate-limits).
* Usually limited to the comment author or moderators.
* Keep edits short and auditable.
---
---
url: /operations/blogUpdatePost.md
---
Update an existing blog post.
Auth: session + owner/admin.
## Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| `id` | path | string | Yes | Post id |
## Request Body
```json
{
"title": "Updated title",
"body": "Updated body",
"lang": "es",
"custom_fields": { "client": "Acme Corp" }
}
```
## Response 200
```json
{
"data": {
"id": "post_2",
"updated": true,
"post_type": "case-study",
"custom_fields": { "client": "Acme Corp" }
},
"user_context": { "authenticated": true },
"meta": {}
}
```
## Response Errors
* `400` invalid update payload (`CUSTOM_FIELDS_*`, `POST_TYPE_LOCKED`, …)
* `401` missing session
* `403` not owner/admin or `APPROVAL_REQUIRED` on publish
* `404` post not found
* `429` `RATE_LIMIT_EXCEEDED`
## Notes
* Rate limit: `post` bucket, 10 requests / 3600s by default. A session that can publish (`admin`, `superadmin`, `author`, `editor`, or the roles in `BLOG_ALLOWED_POST_ROLES` and `BLOG_ADMIN_ROLES`) is not counted. Otherwise `429` `RATE_LIMIT_EXCEEDED`. See [Rate limits](/api/blog#rate-limits).
* Use this for content edits and metadata changes.
* `lang` is an ISO 639-1 code, for example `"lang": "es"`. See [Languages](/api/blog#languages). Omit it to keep the current language.
* Keep slug and visibility in sync with the publishing flow.
* CPT: `custom_fields` are updatable; changing `post_type` returns `POST_TYPE_LOCKED`.
* Type behaviors may still apply on publish (approval, scheduling, password visibility).
---
---
url: /operations/blogUpdateTag.md
---
## Request Body
`name`, `slug`, `description`, and `lang` are optional. `lang` must be an ISO 639-1 code. When `lang` is sent, it replaces the tag language.
## Notes
* Rate limit: `post` bucket, 10 requests / 3600s by default. A session that can publish (`admin`, `superadmin`, `author`, `editor`, or the roles in `BLOG_ALLOWED_POST_ROLES` and `BLOG_ADMIN_ROLES`) is not counted. Otherwise `429` `RATE_LIMIT_EXCEEDED`. See [Rate limits](/api/blog#rate-limits).
---
---
url: /operations/blogUpdateTranslation.md
---
Update a blog translation.
Auth: session + owner/admin.
## Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| `id` | path | string | Yes | Post id |
| `lang` | path | string | Yes | Language code |
## Request Body
```json
{
"title": "Hola mundo (actualizado)",
"body": "# Hola actualizado"
}
```
## Response 200
```json
{
"data": { "id": "post_2", "lang": "es", "updated": true },
"user_context": { "authenticated": true },
"meta": {}
}
```
## Response Errors
* `400` invalid translation payload
* `401` missing session
* `403` not owner/admin
* `404` translation not found
* `429` `RATE_LIMIT_EXCEEDED`
## Notes
* Rate limit: `post` bucket, 10 requests / 3600s by default. A session that can publish (`admin`, `superadmin`, `author`, `editor`, or the roles in `BLOG_ALLOWED_POST_ROLES` and `BLOG_ADMIN_ROLES`) is not counted. Otherwise `429` `RATE_LIMIT_EXCEEDED`. See [Rate limits](/api/blog#rate-limits).
* Use this for translation fixes and editorial updates.
* Keep the language code explicit in the route.
---
---
url: /operations/postTypesUpdate.md
---
Update a post type definition. `type_key` cannot change.
Auth: session + post-types admin role.
## Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| `key` | path | string | Yes | `type_key` |
## Request Body
```json
{
"type_name": "Case Study",
"field_schema": [
{
"name": "client",
"label": "Client",
"type": "text",
"required": true
}
],
"behaviors": {
"requires_approval": true
},
"is_active": true
}
```
## Response 200
```json
{
"data": {
"type_key": "case-study",
"type_name": "Case Study",
"updated_at": "2026-08-06T12:00:00.000Z"
}
}
```
## Response Errors
* `400` invalid payload
* `401` missing session
* `403` insufficient role
* `404` type not found
* `503` `MODULE_DISABLED`
## Notes
* `type_key` is locked on update.
* Changing `field_schema` affects validation of future `custom_fields` on posts.
---
---
url: /operations/adminUpdateUser.md
---
---
---
url: /api/user-profile-update.md
---
---
---
url: /operations/updateUserProfile.md
---
## Behavior Notes
* Endpoint path: `PUT /auth/user/me`
* Core profile fields + optional `is_business` / `biz_*` (requires ext-business; otherwise `400 module_not_installed`).
* Does **not** accept acquisition or privacy fields — use [onboarding complete](/operations/onboardingComplete) or [privacy routes](/api/privacy).
* Session auth; surgical cache update after success.
* A new `email` does **not** write `users.email`. Flowless emails a confirmation link to the current address and another to the new address. Both links must be used, in either order. Response may include `email_change_pending: { to, expires_at, awaiting: ["current", "new"] }`. Confirm with [email change](/operations/confirmEmailChange). The current-inbox page can [cancel](/operations/cancelEmailChange).
* Sending `two_factor` returns `400 use_two_factor_toggle`. Use [POST /auth/two\_factor/toggle](/api/two-factor).
---
---
url: /operations/blogUploadFeaturedImage.md
---
## Notes
* Rate limit: `post` bucket, 10 requests / 3600s by default. A session that can publish (`admin`, `superadmin`, `author`, `editor`, or the roles in `BLOG_ALLOWED_POST_ROLES` and `BLOG_ADMIN_ROLES`) is not counted. Otherwise `429` `RATE_LIMIT_EXCEEDED`. See [Rate limits](/api/blog#rate-limits).
---
---
url: /operations/uploadProfilePicture.md
---
---
---
url: /guides/user-registration.md
---
# User Registration Guide
Learn how to implement user registration in your application using Flowless.
***
## Overview
User registration is the process of creating a new user account. Flowless provides a simple API endpoint that handles:
* Email/username validation
* Password hashing (Argon2id)
* Session creation
* Email verification (optional)
* User profile creation
***
## Basic Registration Flow
```mermaid
sequenceDiagram
participant User
participant Frontend
participant Flowless
participant Email
User->>Frontend: Fill registration form
Frontend->>Frontend: Validate input
Frontend->>Flowless: POST /auth/register
Flowless->>Flowless: Validate & hash password
Flowless->>Flowless: Create user & session
alt Email verification enabled
Flowless->>Email: Send verification email
Flowless-->>Frontend: User created (unverified)
Email->>User: Verification link
User->>Flowless: Click verification link
Flowless-->>User: Email verified
else Email verification disabled
Flowless-->>Frontend: User created (verified)
end
Frontend-->>User: Registration successful
```
***
## Implementation
### Frontend (React)
```typescript
import { useState } from 'react';
interface RegisterFormData {
email: string;
password: string;
name: string;
last_name: string;
}
function RegisterForm() {
const [formData, setFormData] = useState({
email: '',
password: '',
name: '',
last_name: '',
});
const [errors, setErrors] = useState([]);
const [loading, setLoading] = useState(false);
const validateForm = (): boolean => {
const newErrors: string[] = [];
// Email validation
if (!formData.email) {
newErrors.push('Email is required');
} else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
newErrors.push('Invalid email format');
}
// Password validation
if (!formData.password) {
newErrors.push('Password is required');
} else if (formData.password.length < 8) {
newErrors.push('Password must be at least 8 characters');
} else if (!/[A-Z]/.test(formData.password)) {
newErrors.push('Password must contain uppercase letter');
} else if (!/[a-z]/.test(formData.password)) {
newErrors.push('Password must contain lowercase letter');
} else if (!/[0-9]/.test(formData.password)) {
newErrors.push('Password must contain number');
} else if (!/[!@#$%^&*]/.test(formData.password)) {
newErrors.push('Password must contain special character');
}
// Name validation
if (!formData.name) {
newErrors.push('First name is required');
}
setErrors(newErrors);
return newErrors.length === 0;
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!validateForm()) {
return;
}
setLoading(true);
setErrors([]);
try {
const response = await fetch(
`${import.meta.env.VITE_FLOWLESS_URL}/auth/register`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: formData.email.toLowerCase(),
password: formData.password,
name: formData.name,
last_name: formData.last_name,
}),
}
);
const data = await response.json();
if (!data.success) {
setErrors([data.error]);
return;
}
// Store session ID
localStorage.setItem('session_id', data.data.session.session_id);
localStorage.setItem('user_data', JSON.stringify(data.data.user));
// Redirect to dashboard or show verification message
if (data.data.user.is_verified) {
window.location.href = '/dashboard';
} else {
window.location.href = '/verify-email';
}
} catch (error) {
setErrors(['Registration failed. Please try again.']);
} finally {
setLoading(false);
}
};
return (
Create Account
{errors.length > 0 && (
{errors.map((error, index) => (
{error}
))}
)}
setFormData({ ...formData, email: e.target.value })}
required
/>
setFormData({ ...formData, password: e.target.value })}
required
/>
setFormData({ ...formData, name: e.target.value })}
required
/>
setFormData({ ...formData, last_name: e.target.value })}
/>
{loading ? 'Creating Account...' : 'Sign Up'}
);
}
export default RegisterForm;
```
***
## API Reference
### Endpoint
```http
POST /auth/register
```
### Request Body
```json
{
"email": "user@example.com",
"password": "SecurePassword123!",
"name": "John",
"last_name": "Doe",
"username": "johndoe",
"phone": "+1234567890"
}
```
### Response
```json
{
"success": true,
"data": {
"user": {
"id": "usr_1234567890",
"email": "user@example.com",
"name": "John",
"last_name": "Doe",
"is_verified": false,
"created_at": "2025-12-07T10:00:00Z"
},
"session": {
"session_id": "ses_abcdefghijk",
"expires_at": "2025-12-14T10:00:00Z"
}
}
}
```
***
## Best Practices
### 1. Validate on Frontend
Always validate user input before sending to the API:
```typescript
function validateEmail(email: string): boolean {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}
function validatePassword(password: string): boolean {
return (
password.length >= 8 &&
/[A-Z]/.test(password) &&
/[a-z]/.test(password) &&
/[0-9]/.test(password) &&
/[!@#$%^&*]/.test(password)
);
}
```
### 2. Normalize Email
Always convert email to lowercase:
```typescript
const email = userInput.toLowerCase().trim();
```
### 3. Show Password Strength
```typescript
function getPasswordStrength(password: string): string {
let strength = 0;
if (password.length >= 8) strength++;
if (password.length >= 12) strength++;
if (/[A-Z]/.test(password)) strength++;
if (/[a-z]/.test(password)) strength++;
if (/[0-9]/.test(password)) strength++;
if (/[!@#$%^&*]/.test(password)) strength++;
if (strength <= 2) return 'Weak';
if (strength <= 4) return 'Medium';
return 'Strong';
}
```
### 4. Handle Errors Gracefully
```typescript
try {
const response = await register(formData);
} catch (error) {
if (error.message === 'Email already registered') {
setErrors(['This email is already in use. Try logging in instead.']);
} else {
setErrors(['Registration failed. Please try again.']);
}
}
```
***
## Next Steps
* [**Login Flow**](/guides/login-flow) - Implement login
* [**Email Verification**](/guides/email-verification) - Verify user emails
* [**Password Reset**](/guides/password-reset) - Reset passwords
* [**Social Login**](/guides/social-login) - Add OAuth
---
---
url: /api/users.md
---
# Users API
Manage user profiles, update information, and handle account operations.
::: tip 📖 Real API Documentation
All endpoints are documented based on the actual Flowless backend code - guaranteed to match production behavior!
:::
***
## Base URL
```
https://your-instance-name.pubflow.com
```
***
## Get User Profile
Get the authenticated user's complete profile.
### Endpoint
```http
GET /auth/me
```
**Alternative endpoint:**
```http
GET /auth/user/me
```
### Headers
```http
X-Session-ID: ses_xyz123456
```
### Response
```json
{
"success": true,
"data": {
"user": {
"id": "usr_1234567890",
"email": "user@example.com",
"name": "John",
"last_name": "Doe",
"user_name": "johndoe",
"user_type": "customer",
"picture": "https://storage.pubflow.com/users/usr_123/picture.jpg",
"phone": "+1234567890",
"is_verified": true,
"two_factor": false,
"dob": "1990-01-01",
"gender": "m",
"title": "mr",
"reference_id": "ref_123",
"recovery_email": "recovery@example.com",
"tmz": "America/New_York",
"created_at": "2025-12-07T10:00:00Z",
"updated_at": "2025-12-07T10:00:00Z"
}
}
}
```
***
## Update User Profile
Update user profile information.
### Endpoint
```http
PUT /auth/profile
```
**Alternative endpoint (with enhanced validation):**
```http
PUT /auth/user/me
```
### Headers
```http
X-Session-ID: ses_xyz123456
Content-Type: application/json
```
### Request Body
```json
{
"name": "John",
"lastName": "Doe",
"userName": "johndoe",
"phone": "+1234567890",
"dob": "1990-01-01",
"gender": "m",
"title": "mr",
"referenceId": "ref_123",
"recoveryEmail": "recovery@example.com",
"tmz": "America/New_York"
}
```
### Parameters
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | No | User's first name |
| `lastName` | string | No | User's last name |
| `userName` | string | No | Unique username |
| `phone` | string | No | Phone number |
| `dob` | string | No | Date of birth (YYYY-MM-DD) |
| `gender` | string | No | ISO 5218: `m`, `f`, `x` |
| `title` | string | No | Courtesy honorific (`mr`, `mrs`, `ms`, `miss`, `mx`, `mstr`, `dr`, `prof`, `rev`, `hon`, `sir`, `dame`, `lord`, `lady`, `capt`). Null/empty = none. Not job title (`biz_position`). |
| `referenceId` | string | No | External reference ID |
| `recoveryEmail` | string | No | Recovery email address |
| `tmz` | string | No | Timezone (e.g., "America/New\_York") |
::: info Email and 2FA
* `email` — requesting a new address starts a pending change. Both the current inbox and the new inbox must confirm `GET`/`POST /auth/email-change/verify`, in either order. The profile JSON still shows the current email until the second confirmation. The current-inbox page can reject the request (“this wasn’t me”).
* `two_factor` — not accepted here (`400 use_two_factor_toggle`). Use `POST /auth/two_factor/toggle` with an OTP when disabling.
* `mobile` - Mobile number
* `bio` - User biography
* `display_name` - Display name
* `first_time` - First time user flag
* `title` - Courtesy title / honorific (language-agnostic codes; not `biz_position`)
* `metadata` - Custom JSON metadata
:::
### Response
```json
{
"success": true,
"data": {
"user": {
"id": "usr_1234567890",
"email": "user@example.com",
"name": "John",
"lastName": "Doe",
"userName": "johndoe",
"userType": "customer",
"picture": null,
"phone": "+1234567890",
"isVerified": true,
"twoFactor": false,
"dob": "1990-01-01",
"gender": "m",
"title": "mr",
"reference_id": "ref_123",
"recovery_email": "recovery@example.com",
"tmz": "America/New_York",
"updatedAt": "2025-12-07T11:00:00Z"
}
}
}
```
***
## Upload Profile Picture
Upload or update user's profile picture.
### Endpoint
```http
POST /auth/upload/picture
```
### Headers
```http
X-Session-ID: ses_xyz123456
Content-Type: multipart/form-data
```
### Request Body (Form Data)
```
picture: [File]
```
### Supported Formats
* JPEG (.jpg, .jpeg)
* PNG (.png)
* WebP (.webp)
* GIF (.gif)
* Max size: 10MB
* Automatic compression and optimization
### Response
```json
{
"success": true,
"data": {
"picture_url": "https://storage.pubflow.com/users/usr_1234567890/picture.jpg",
"file_size": 245678,
"original_size": 512000,
"compression_ratio": 0.48,
"method": "cloud_config"
},
"message": "Picture uploaded successfully",
"timestamp": "2025-12-07T11:00:00Z"
}
```
### Example (JavaScript)
```javascript
async function uploadProfilePicture(file: File) {
const formData = new FormData();
formData.append('picture', file);
const response = await fetch(
`${FLOWLESS_URL}/auth/upload/picture`,
{
method: 'POST',
headers: {
'X-Session-ID': sessionId,
},
body: formData,
}
);
const data = await response.json();
return data.data.picture_url;
}
```
***
## Delete Profile Picture
Delete user's profile picture.
### Endpoint
```http
DELETE /auth/upload/picture
```
### Headers
```http
X-Session-ID: ses_xyz123456
```
### Response
```json
{
"success": true,
"message": "Picture deleted successfully"
}
```
***
## Change Password
Change the user's password (authenticated users).
### Endpoint
```http
POST /auth/password-change/self
```
### Headers
```http
X-Session-ID: ses_xyz123456
Content-Type: application/json
```
### Request Body
```json
{
"currentPassword": "OldPassword123!",
"newPassword": "NewPassword456!"
}
```
### Response
```json
{
"success": true,
"message": "Password updated successfully"
}
```
### Error Responses
```json
// Incorrect current password
{
"success": false,
"error": "Current password is incorrect"
}
// Weak new password
{
"success": false,
"error": "New password must be at least 8 characters long"
}
```
***
## Request Password Reset
Request a password reset email.
### Endpoint
```http
POST /auth/password-reset/request
```
### Request Body
```json
{
"email": "user@example.com"
}
```
### Response
```json
{
"success": true,
"message": "If your email is registered, you will receive password reset instructions."
}
```
::: tip Security Feature
This endpoint always returns success, even if the email doesn't exist, to prevent email enumeration attacks.
:::
***
## Validate Password Reset Token
Validate a password reset token before using it.
### Endpoint
```http
POST /auth/password-reset/validate
```
### Request Body
```json
{
"token": "reset_token_abc123"
}
```
### Response
```json
{
"valid": true,
"message": "Token is valid"
}
```
***
## Reset Password
Reset password using the token from the email.
### Endpoint
```http
POST /auth/password-reset/complete
```
### Request Body
```json
{
"token": "reset_token_abc123",
"password": "NewPassword456!"
}
```
### Response
```json
{
"success": true,
"message": "Password reset successfully"
}
```
### Error Responses
```json
// Invalid or expired token
{
"success": false,
"error": "Invalid or expired reset token"
}
// Weak password
{
"success": false,
"error": "Password must be at least 8 characters long"
}
```
***
## Resend Verification Email
Resend the email verification email.
### Endpoint
```http
POST /auth/resend-verification
```
### Headers
```http
X-Bridge-Secret: your_bridge_secret
Content-Type: application/json
```
### Request Body
```json
{
"email": "user@example.com"
}
```
### Response
```json
{
"success": true,
"message": "If your email is registered, you will receive a verification email.",
"verification_sent": true
}
```
::: warning Requires Bridge Secret
This endpoint requires the `X-Bridge-Secret` header for security. Get your bridge secret from the Pubflow dashboard.
:::
***
## Admin - Search Users
Search and filter users (admin/superadmin only).
### Endpoint
```http
GET /auth/users
```
### Headers
```http
X-Session-ID: ses_admin_xyz
```
### Query Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `q` | string | No | Search query (email, name, username) |
| `userType` | string | No | Filter by user type |
| `page` | number | No | Page number (default: 1) |
| `limit` | number | No | Results per page (default: 10) |
### Example Request
```http
GET /auth/users?q=john&userType=customer&page=1&limit=10
```
### Response
```json
{
"success": true,
"data": {
"users": [
{
"id": "usr_abc123",
"email": "user@example.com",
"name": "John",
"lastName": "Doe",
"userName": "johndoe",
"userType": "customer",
"isVerified": true,
"createdAt": "2025-12-07T10:00:00Z"
}
],
"pagination": {
"page": 1,
"limit": 10,
"total": 1,
"pages": 1
}
}
}
```
***
## Admin - Get User Details
Get detailed information about a specific user (admin/superadmin only).
### Endpoint
```http
GET /auth/admin/users/:id
```
### Headers
```http
X-Session-ID: ses_admin_xyz
```
### Response
```json
{
"success": true,
"data": {
"id": "usr_abc123",
"email": "user@example.com",
"name": "John",
"last_name": "Doe",
"user_type": "customer",
"picture": null,
"user_name": "johndoe",
"phone": "+1234567890",
"is_verified": true,
"two_factor": false,
"created_at": "2025-12-07T10:00:00Z",
"updated_at": "2025-12-07T11:00:00Z",
"sessions": [
{
"id": "ses_xyz789",
"sessionPrefix": "ses_xyz",
"ipAddress": "192.168.1.1",
"userAgent": "Mozilla/5.0...",
"userDevice": "desktop",
"lastUsedAt": "2025-12-07T11:00:00Z",
"createdAt": "2025-12-07T10:00:00Z",
"expiresAt": "2025-12-14T10:00:00Z",
"status": "active"
}
],
"sessionCount": 1
}
}
```
***
## Admin - Update User
Update any user's information (admin/superadmin only).
### Endpoint
```http
PUT /auth/admin/users/:id
```
### Headers
```http
X-Session-ID: ses_admin_xyz
Content-Type: application/json
```
### Request Body
```json
{
"name": "John",
"last_name": "Doe",
"user_name": "johndoe",
"email": "newemail@example.com",
"phone": "+1234567890",
"is_verified": true,
"two_factor": false,
"user_type": "customer",
"dob": "1990-01-01",
"gender": "m",
"title": "mr",
"reference_id": "ref_123",
"recovery_email": "recovery@example.com",
"tmz": "America/New_York"
}
```
### Response
```json
{
"success": true,
"data": {
"id": "usr_abc123",
"email": "newemail@example.com",
"name": "John",
"last_name": "Doe",
"user_type": "customer",
"user_name": "johndoe",
"picture": null,
"phone": "+1234567890",
"is_verified": true,
"two_factor": false,
"dob": "1990-01-01",
"gender": "m",
"title": "mr",
"reference_id": "ref_123",
"recovery_email": "recovery@example.com",
"tmz": "America/New_York",
"created_at": "2025-12-07T10:00:00Z",
"updated_at": "2025-12-07T12:00:00Z"
}
}
```
::: warning Permission Restrictions
* Only superadmin can modify superadmin users
* Only superadmin can change user\_type to/from superadmin
* Admins cannot modify users with higher privileges
:::
***
## Admin - Change User Password
Change any user's password (admin/superadmin only).
### Endpoint
```http
POST /auth/password-change/admin
```
### Headers
```http
X-Session-ID: ses_admin_xyz
Content-Type: application/json
```
### Request Body
```json
{
"userId": "usr_abc123",
"newPassword": "NewPassword456!"
}
```
### Response
```json
{
"success": true,
"message": "Password updated successfully. User will need to log in again."
}
```
::: info Session Invalidation
All active sessions for the user will be invalidated, forcing them to log in again with the new password.
:::
***
## Rate Limiting
User endpoints are rate-limited for security:
| Endpoint | Limit | Window |
|----------|-------|--------|
| `GET /auth/me` | 100 requests | 1 minute |
| `PUT /auth/profile` | 10 requests | 1 minute |
| `POST /auth/upload/picture` | 5 requests | 1 hour |
| `POST /auth/password-change/self` | 5 requests | 1 hour |
| `POST /auth/password-reset/request` | 3 requests | 1 hour |
| `POST /auth/resend-verification` | 3 requests | 1 hour |
***
## Next Steps
* [**API Playground**](/playground) - Test all endpoints interactively
* [**Authentication API**](/api/authentication) - Login and registration
* [**Sessions API**](/api/sessions) - Session management
* [**Flowfull Clients**](https://clients.flowfull.dev/) - Pre-built UI components
* [**Discord Community**](https://discord.gg/EJfPTT6Vh7) - Get help
---
---
url: /api/password-reset-validate.md
---
---
---
url: /operations/validatePasswordResetToken.md
---
---
---
url: /api/session-validation.md
---
---
---
url: /operations/validateSession.md
---
## Behavior Notes
* Full session: success=true and includes user/session data.
* Pending 2FA session: success=false with requires\_2fa=true, sessionId, available\_methods, and user.
---
---
url: /operations/bridgeValidateSession.md
---
---
---
url: /api/token-validate.md
---
---
---
url: /operations/validateToken.md
---
---
---
url: /operations/validateTokenGet.md
---
---
---
url: /operations/twoFactorVerify.md
---
---
---
url: /introduction.md
---
# What is Flowless?
**Flowless** is a fully managed authentication backend service provided by Pubflow. It handles all aspects of user authentication, session management, and security for your applications, allowing you to focus on building your core product.
***
## Overview
Flowless is designed to be the authentication layer for modern applications. Instead of building and maintaining your own authentication system, you create a Flowless instance on [Pubflow.com](https://pubflow.com) and integrate it with your application through a simple REST API.
### Key Characteristics
* **Fully Managed** - Pubflow handles deployment, scaling, updates, and maintenance
* **Production Ready** - Enterprise-grade security and 99.9% uptime SLA
* **Developer Friendly** - RESTful API with comprehensive documentation
* **Framework Agnostic** - Works with any frontend or backend technology
* **Scalable** - Automatically scales from 10 to 10 million users
***
## Core Responsibilities
Flowless handles everything related to user authentication and management:
### 1. User Authentication
* Email/password registration and login
* Username-based authentication
* Email verification
* Password reset flows
* Multi-factor authentication (coming soon)
### 2. Session Management
* Secure session creation and validation
* Session refresh mechanism
* Multi-device session support
* Device-bound sessions
* Automatic session cleanup
### 3. Social Authentication
* OAuth 2.0 integration
* Supported providers:
* Google
* Facebook
* GitHub
* Twitter
* LinkedIn
* Custom OAuth providers
### 4. User Management
* User profile management
* Account deletion
* User search (admin)
* Ban/unban users (admin)
* Custom user metadata
### 5. Token Authentication
* API token generation
* Token-based login
* Token validation
* Token revocation
### 6. Security Features
* Argon2 password hashing
* Session encryption (SHA-256)
* Rate limiting
* IP validation
* Device fingerprinting
* Automatic DDoS protection
### 7. Email Service
* Email verification
* Password reset emails
* Custom email templates
* Multi-language support
* ZeptoMail integration
### 8. Bridge Validation
* Trust token generation (PASETO)
* Secure backend communication
* Validation modes: STANDARD, ADVANCED, STRICT
* IP and device validation
### 9. Modules and Extensions
* Module Hub for installing and updating product extensions
* Blog module for content, posts, categories, comments, and publishing flows
* Post Types (CPT) for typed content on top of Blog
* Onboarding for first-run wizard fields on `users` (acquisition, business, privacy)
* Business (onboarding extension) for company profile via `PUT /auth/user/me`
* Privacy (onboarding extension) for GDPR/CCPA self-service
* Two-Factor Authentication for login-time verification
* Two-Factor Authentication module for login-time security hardening
### Available Modules Today
| Module | What it does | Best reference |
|--------|--------------|----------------|
| Module Hub | Installs, updates, repairs, and audits modules | [API Modules](/api/modules) |
| Blog | Adds the modular post system and blog routes | [Blog API](/api/blog) |
| Post Types | Custom content types and `custom_fields` on Blog | [Post Types API](/api/post-types) |
| Onboarding | First-run complete + acquisition / biz / privacy on `users` | [Onboarding API](/api/onboarding) |
| Business | `is_business` / `biz_*` via profile PUT (`ext-business`) | [Business API](/api/business) |
| Privacy | GDPR/CCPA routes under `/auth/user/me/privacy*` | [Privacy API](/api/privacy) |
| Two-Factor Authentication | Adds the full 2FA flow with pending sessions and code verification | [2FA API](/api/two-factor) |
***
## How It Works
```mermaid
sequenceDiagram
participant User
participant Frontend
participant Flowfull
participant Flowless
User->>Frontend: Enter credentials
Frontend->>Flowless: POST /auth/login
Flowless->>Flowless: Validate & create session
Flowless-->>Frontend: Return session_id
Frontend->>Flowfull: API call with session_id
Flowfull->>Flowless: Validate session (Bridge)
Flowless-->>Flowfull: Trust token + user data
Flowfull-->>Frontend: Protected resource
```
### The Flow
1. **User Authentication** - Your frontend calls Flowless to register/login users
2. **Session Creation** - Flowless creates a secure session and returns a session ID
3. **API Calls** - Your frontend includes the session ID in requests to your backend
4. **Session Validation** - Your backend (Flowfull) validates the session with Flowless
5. **Trust Token** - Flowless returns a trust token with user data
6. **Protected Resources** - Your backend serves the protected resource
***
## What Flowless is NOT
It's important to understand what Flowless doesn't do:
* ❌ **Not a complete backend** - You still need your own backend (Flowfull) for business logic
* ❌ **Not a database** - You manage your own application data
* ❌ **Not self-hosted** - Flowless is a managed service only
* ❌ **Not a CMS** - It's purely for authentication and user management
***
## Flowless vs. Traditional Auth
| Feature | Flowless | Traditional Auth |
|---------|----------|------------------|
| **Deployment** | Instant (create instance) | Days/weeks of setup |
| **Maintenance** | Fully managed by Pubflow | You maintain everything |
| **Security Updates** | Automatic | Manual updates required |
| **Scaling** | Automatic | Manual scaling |
| **Cost** | Pay per user | Infrastructure + dev time |
| **Compliance** | GDPR, SOC 2 included | You handle compliance |
| **Monitoring** | Built-in dashboard | Build your own |
| **Email Service** | Included | Integrate separately |
***
## Use Cases
Flowless is perfect for:
✅ **SaaS Applications** - Multi-tenant apps with user authentication\
✅ **Mobile Apps** - React Native, Flutter, native iOS/Android\
✅ **Web Applications** - React, Next.js, Vue, Angular\
✅ **API Services** - Token-based authentication for APIs\
✅ **Marketplaces** - User registration and social login\
✅ **Internal Tools** - Admin dashboards and employee portals
***
## Next Steps
Ready to get started?
* [**Getting Started**](/getting-started) - Create your first instance
* [**Modules**](/modules/index) - See the available extensions and the Module Hub
* [**Core Concepts**](/core-concepts) - Understand key concepts
* [**Architecture**](/architecture) - Learn about the architecture
* [**API Reference**](/api/authentication) - Explore the API
---
---
url: /operations/deleteGdprConsent.md
---
Path: `DELETE /auth/user/me/privacy/gdpr-consent`\
Sets `gdpr_consent=false`. Historical `gdpr_consent_at` / version retained for audit.