HIVE

Local Setup

Supabase Setup

Supabase Setup

This guide covers setting up Supabase for HIVE Protocol, including database configuration, authentication, and running migrations.

Overview

Supabase provides:

  • PostgreSQL Database: Stores all application data
  • Authentication: User signup, login, and session management
  • Realtime: Live updates via WebSocket subscriptions
  • Edge Functions: Serverless functions for AI integration
  • Storage: File uploads (avatars, attachments)
┌─────────────────────────────────────────────────────────────────┐
│                    Supabase Architecture                         │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  ┌─────────────┐       ┌─────────────┐       ┌─────────────┐    │
│  │   Client    │ ───── │  Supabase   │ ───── │  PostgreSQL │    │
│  │   (React)   │       │    API      │       │   Database  │    │
│  └─────────────┘       └─────────────┘       └─────────────┘    │
│         │                     │                     │            │
│         │              ┌──────┴──────┐              │            │
│         │              │             │              │            │
│         │        ┌─────┴────┐ ┌──────┴─────┐       │            │
│         └─────── │   Auth   │ │  Realtime  │ ──────┘            │
│                  │  (JWT)   │ │ (WebSocket)│                    │
│                  └──────────┘ └────────────┘                    │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

Cloud Supabase Setup

Create a Project

  1. Go to supabase.com/dashboard
  2. Click "New Project"
  3. Fill in project details:
  4. Name: hive-protocol-dev
  5. Database Password: Generate a strong password
  6. Region: Select closest to your location
  7. Click "Create new project"
  8. Wait for project initialization (2-3 minutes)

Get API Credentials

Navigate to Project Settings > API:

# Project URL
NEXT_PUBLIC_SUPABASE_URL=https://xxxxxxxxxxxx.supabase.co

# anon/public key (safe for client-side)
NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

# service_role key (server-side only - keep secret!)
SUPABASE_SERVICE_ROLE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Configure Authentication

Navigate to Authentication > Providers:

Email Provider:
  - Enable Email: ON
  - Confirm Email: OFF (for development)
  - Secure Email Change: ON
  - Double Confirm Changes: OFF (for development)

Site URL: http://localhost:3000

Redirect URLs:
  - http://localhost:3000/**
  - http://localhost:3000/auth/callback

Configure Email Templates (Optional)

Navigate to Authentication > Email Templates:

<!-- Customize welcome email -->
<h2>Welcome to HIVE Protocol!</h2>
<p>Click below to confirm your email:</p>
<a href="{{ .ConfirmationURL }}">Confirm Email</a>

Running Migrations

HIVE Protocol uses database migrations to set up the schema.

Option 1: Via Supabase Dashboard

  1. Navigate to SQL Editor in your Supabase dashboard
  2. Open each migration file in order (by timestamp)
  3. Copy the SQL content
  4. Paste into SQL Editor
  5. Click "Run"

Migration files are in supabase/migrations/:

20260107174235_create_hive_schema.sql
20260107213957_create_activity_log.sql
20260107222724_add_swarm_sharing.sql
... (run all in order)

Option 2: Via Supabase CLI

# Install Supabase CLI
npm install -g supabase

# Login to Supabase
supabase login

# Link to your project
supabase link --project-ref your-project-ref

# Push all migrations
supabase db push

# Check migration status
supabase migration list

Verify Database Setup

After running migrations, verify tables exist:

-- Run in SQL Editor
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public'
ORDER BY table_name;

You should see tables like:

  • agents
  • swarms
  • swarm_agents
  • messages
  • context_blocks
  • tools
  • webhooks
  • profiles
  • etc.

Row Level Security (RLS)

All tables have RLS enabled for security. Verify policies:

-- Check RLS is enabled
SELECT tablename, rowsecurity
FROM pg_tables
WHERE schemaname = 'public';

-- View policies
SELECT tablename, policyname, permissive, roles, cmd, qual
FROM pg_policies
WHERE schemaname = 'public'
ORDER BY tablename;

Key RLS Policies

-- Users can only access their own agents
CREATE POLICY "Users can view own agents"
  ON agents FOR SELECT TO authenticated
  USING (auth.uid() = user_id);

-- Users can only access their own swarms (or shared ones)
CREATE POLICY "Users can view own swarms"
  ON swarms FOR SELECT TO authenticated
  USING (
    auth.uid() = user_id OR
    visibility = 'public' OR
    EXISTS (
      SELECT 1 FROM swarm_shares
      WHERE swarm_id = swarms.id
      AND shared_with = auth.uid()
    )
  );

-- Messages visible if user can access the swarm
CREATE POLICY "Users can view swarm messages"
  ON messages FOR SELECT TO authenticated
  USING (
    EXISTS (
      SELECT 1 FROM swarms
      WHERE swarms.id = messages.swarm_id
      AND (swarms.user_id = auth.uid() OR swarms.visibility = 'public')
    )
  );

Realtime Setup

Enable realtime for specific tables:

  1. Navigate to Database > Replication
  2. Enable publication for tables:
  3. messages
  4. agents (status updates)
  5. swarms
  6. swarm_presence

Or via SQL:

-- Enable realtime for messages
ALTER PUBLICATION supabase_realtime ADD TABLE messages;
ALTER PUBLICATION supabase_realtime ADD TABLE agents;
ALTER PUBLICATION supabase_realtime ADD TABLE swarm_presence;

Storage Setup

Create storage bucket for avatars:

  1. Navigate to Storage
  2. Click "New Bucket"
  3. Name: avatars
  4. Public: Yes (for avatar URLs)

Or the migration handles this:

-- Create avatars bucket (from migration)
INSERT INTO storage.buckets (id, name, public)
VALUES ('avatars', 'avatars', true)
ON CONFLICT DO NOTHING;

-- Allow authenticated users to upload avatars
CREATE POLICY "Users can upload avatars"
  ON storage.objects FOR INSERT TO authenticated
  WITH CHECK (bucket_id = 'avatars' AND auth.uid()::text = (storage.foldername(name))[1]);

Testing the Setup

Test Authentication

import { supabase } from '@/lib/supabase';

// Test signup
const { data, error } = await supabase.auth.signUp({
  email: 'test@example.com',
  password: 'testpassword123'
});

console.log('Signup result:', data, error);

Test Database Access

// After signing in, test table access
const { data: agents, error } = await supabase
  .from('agents')
  .select('*');

console.log('Agents:', agents, error);

Test Realtime

// Subscribe to messages
const channel = supabase
  .channel('test-channel')
  .on(
    'postgres_changes',
    { event: 'INSERT', schema: 'public', table: 'messages' },
    (payload) => console.log('New message:', payload)
  )
  .subscribe();

Local Supabase (Optional)

For offline development, you can run Supabase locally.

Prerequisites

  • Docker Desktop installed and running
  • Supabase CLI installed

Start Local Supabase

# Initialize local config (if not exists)
supabase init

# Start local services
supabase start

# This starts:
# - PostgreSQL on localhost:54322
# - Studio on localhost:54323
# - API on localhost:54321
# - Realtime on localhost:54322

# Get local credentials
supabase status

Local Environment Variables

# .env.local for local development
NEXT_PUBLIC_SUPABASE_URL=http://localhost:54321
NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
SUPABASE_SERVICE_ROLE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Stop Local Supabase

# Stop all services
supabase stop

# Stop and reset data
supabase stop --no-backup

Database Maintenance

View Table Statistics

SELECT
  schemaname,
  relname AS table_name,
  n_live_tup AS row_count
FROM pg_stat_user_tables
ORDER BY n_live_tup DESC;

Vacuum Tables

-- Reclaim storage and update statistics
VACUUM ANALYZE agents;
VACUUM ANALYZE swarms;
VACUUM ANALYZE messages;

Backup Database

  1. Navigate to Project Settings > Database
  2. Click "Download backup"

Or use CLI:

# Create backup
supabase db dump -f backup.sql

# Restore backup
supabase db reset
psql -h localhost -p 54322 -U postgres -d postgres -f backup.sql

Troubleshooting

Connection Issues

# Test connection
curl https://your-project.supabase.co/rest/v1/ \
  -H "apikey: your-anon-key"

# Should return empty array or data, not error

RLS Blocking Access

-- Temporarily check what user sees
SET request.jwt.claims = '{"sub": "user-uuid-here"}';
SELECT * FROM agents;

Migration Errors

# Check migration status
supabase migration list

# Repair migrations
supabase migration repair --status applied 20260107174235

Next Steps

  • [Edge Functions](/docs/local-setup/edge-functions): Deploy serverless functions
  • [Troubleshooting](/docs/local-setup/troubleshooting): Common issues
  • [Authentication](/docs/api/authentication): Auth API reference

Cookie Preferences

We use cookies to enhance your experience, analyze site traffic, and for marketing purposes. By clicking "Accept All", you consent to our use of cookies. Read our Privacy Policy for more information.