Supabase Setup Guide for ContextWeave

This guide covers setting up Supabase for ContextWeave, including database configuration, authentication, and Row Level Security (RLS) policies.

Overview

Supabase provides:

  • PostgreSQL Database - For storing user profiles and generation history
  • Authentication - GitHub OAuth and email/password
  • Real-time subscriptions - For live updates
  • Row Level Security - For data protection
  • Edge Functions - For serverless backend logic

Initial Supabase Setup

1. Create Supabase Project

# Go to supabase.com and: 1. Sign up/login to Supabase 2. Click "New Project" 3. Choose organization 4. Enter project details: - Name: contextweave - Database Password: (generate strong password) - Region: (closest to your users) 5. Click "Create new project"

2. Get Project Credentials

# In Supabase dashboard, go to Settings > API # Copy these values: Project URL: https://your-project-id.supabase.co Anon Key: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... Service Role Key: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

3. Configure Environment Variables

In Bolt.new, add these environment variables:

# Public keys (safe for frontend) NEXT_PUBLIC_SUPABASE_URL=https://your-project-id.supabase.co NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... # Private keys (backend only) SUPABASE_SERVICE_ROLE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Database Schema Setup

1. Run Database Migrations

The migration file is already created at supabase/migrations/20250630043623_lingering_rice.sql.

Option A: Using Supabase Dashboard (Recommended)

-- Go to Supabase Dashboard > SQL Editor -- Copy and paste the entire migration file content -- Click "Run" to execute

Option B: Using Supabase CLI (Advanced)

# Install Supabase CLI npm install -g supabase # Login to Supabase supabase login # Link to your project supabase link --project-ref your-project-id # Push migrations supabase db push

2. Verify Database Schema

After running migrations, verify these tables exist:

-- Check tables in Supabase Dashboard > Table Editor - libraries - profiles - profile_chunks - users - api_usage - cache_invalidations

3. Enable Required Extensions

-- These should be enabled by the migration, but verify: -- Go to Database > Extensions in Supabase Dashboard CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; CREATE EXTENSION IF NOT EXISTS vector;

Authentication Setup

1. Configure Auth Providers

# In Supabase Dashboard > Authentication > Providers # Enable Email provider: 1. Click "Email" 2. Enable "Enable email confirmations" = false (for demo) 3. Save # Enable GitHub provider: 1. Click "GitHub" 2. Enable the provider 3. Add GitHub OAuth credentials: - Client ID: (from GitHub OAuth app) - Client Secret: (from GitHub OAuth app) 4. Save

2. Create GitHub OAuth App

# Go to GitHub > Settings > Developer settings > OAuth Apps 1. Click "New OAuth App" 2. Fill in details: - Application name: ContextWeave - Homepage URL: https://your-app.netlify.app - Authorization callback URL: https://your-project.supabase.co/auth/v1/callback 3. Click "Register application" 4. Copy Client ID and Client Secret to Supabase

3. Configure Auth Settings

# In Supabase Dashboard > Authentication > Settings # Site URL (for redirects) Site URL: https://your-app.netlify.app # Additional redirect URLs https://localhost:3000 https://your-app.netlify.app https://your-custom-domain.com # JWT Settings (default is fine) JWT expiry: 3600 seconds

Row Level Security (RLS) Setup

1. Verify RLS is Enabled

-- Check in Supabase Dashboard > Authentication > Policies -- These tables should have RLS enabled: - libraries (public read, service role write) - profiles (users own data) - profile_chunks (public read, service role write) - users (users own data) - api_usage (users own data)

2. Test RLS Policies

-- Test user can read their own profile SELECT * FROM profiles WHERE user_id = auth.uid(); -- Test user cannot read other profiles SELECT * FROM profiles WHERE user_id != auth.uid(); -- Should return no results

3. Add Custom Policies (if needed)

-- Example: Allow users to read public library data CREATE POLICY "Public libraries are readable" ON libraries FOR SELECT TO authenticated, anon USING (true); -- Example: Allow users to track their API usage CREATE POLICY "Users can view own API usage" ON api_usage FOR SELECT TO authenticated USING (auth.uid() = user_id);

Frontend Integration

1. Supabase Client Setup

The client is already configured in lib/supabase.ts:

import { createClientComponentClient } from '@supabase/auth-helpers-nextjs' export const supabase = createClientComponentClient() // Test the connection export const testConnection = async () => { const { data, error } = await supabase.auth.getSession() console.log('Supabase connection:', { data, error }) }

2. Authentication Integration

// Sign in with GitHub export const signInWithGitHub = async () => { const { error } = await supabase.auth.signInWithOAuth({ provider: 'github', options: { redirectTo: `${window.location.origin}/auth/callback` } }) if (error) throw error } // Sign out export const signOut = async () => { const { error } = await supabase.auth.signOut() if (error) throw error } // Get current user export const getCurrentUser = async () => { const { data: { user }, error } = await supabase.auth.getUser() return { user, error } }

3. Database Operations

// Create user profile export const createProfile = async (profileData: any) => { const { data, error } = await supabase .from('profiles') .insert(profileData) .select() return { data, error } } // Get user profile export const getProfile = async (userId: string) => { const { data, error } = await supabase .from('profiles') .select('*') .eq('user_id', userId) .single() return { data, error } } // Save generation export const saveGeneration = async (generationData: any) => { const { data, error } = await supabase .from('generations') .insert(generationData) .select() return { data, error } }

Testing Supabase Integration

1. Test Database Connection

# In browser console (after app loads): import { supabase } from './lib/supabase' // Test basic connection supabase.auth.getSession().then(console.log) // Test database query supabase.from('libraries').select('*').limit(1).then(console.log)

2. Test Authentication

# Test GitHub OAuth 1. Click "Sign in with GitHub" in app 2. Authorize the application 3. Verify redirect back to app 4. Check user session in browser console: supabase.auth.getUser().then(console.log)

3. Test Database Operations

# Test profile creation (after authentication) const profileData = { user_id: 'user-id-from-auth', libraries: ['react', 'next.js'], frameworks: ['Next.js'], languages: ['TypeScript'] } supabase.from('profiles').insert(profileData).then(console.log)

Production Configuration

1. Security Settings

# In Supabase Dashboard > Settings > API # Rate limiting (adjust based on needs) - Anonymous requests: 100/hour - Authenticated requests: 1000/hour # CORS settings - Allowed origins: your-domain.com, localhost:3000

2. Performance Optimization

-- Add indexes for common queries CREATE INDEX IF NOT EXISTS idx_profiles_user_id ON profiles(user_id); CREATE INDEX IF NOT EXISTS idx_generations_user_id ON generations(user_id); CREATE INDEX IF NOT EXISTS idx_api_usage_user_date ON api_usage(user_id, created_at);

3. Backup Configuration

# In Supabase Dashboard > Settings > Database # Enable automatic backups # Set retention period (7 days recommended)

Monitoring and Maintenance

1. Monitor Usage

# In Supabase Dashboard > Settings > Usage # Monitor: - Database size - API requests - Authentication events - Bandwidth usage

2. Review Logs

# In Supabase Dashboard > Logs # Check for: - Authentication errors - Database errors - Policy violations - Performance issues

3. Regular Maintenance

-- Clean up old data (run monthly) DELETE FROM api_usage WHERE created_at < NOW() - INTERVAL '90 days'; DELETE FROM cache_invalidations WHERE created_at < NOW() - INTERVAL '7 days'; -- Analyze table statistics ANALYZE profiles; ANALYZE generations; ANALYZE api_usage;

Troubleshooting

1. Connection Issues

# Check environment variables console.log(process.env.NEXT_PUBLIC_SUPABASE_URL) console.log(process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY) # Test connection manually fetch('https://your-project.supabase.co/rest/v1/', { headers: { 'apikey': 'your-anon-key', 'Authorization': 'Bearer your-anon-key' } })

2. Authentication Issues

# Check OAuth configuration # Verify redirect URLs match exactly # Check GitHub OAuth app settings # Review Supabase auth logs # Test auth flow step by step 1. Click sign in 2. Check redirect to GitHub 3. Authorize app 4. Check redirect back to app 5. Verify session creation

3. Database Issues

# Check RLS policies # Verify user permissions # Review database logs # Test queries manually in SQL editor # Common RLS debugging SELECT auth.uid(); -- Check current user ID SELECT * FROM auth.users; -- Check user exists

4. Performance Issues

# Check query performance EXPLAIN ANALYZE SELECT * FROM profiles WHERE user_id = 'user-id'; # Monitor connection pool # Check for slow queries in logs # Optimize indexes if needed

Migration and Backup

1. Data Export

-- Export user data COPY (SELECT * FROM profiles) TO '/tmp/profiles.csv' WITH CSV HEADER; COPY (SELECT * FROM generations) TO '/tmp/generations.csv' WITH CSV HEADER;

2. Data Import

-- Import data to new instance COPY profiles FROM '/tmp/profiles.csv' WITH CSV HEADER; COPY generations FROM '/tmp/generations.csv' WITH CSV HEADER;

3. Schema Migration

# Use Supabase CLI for schema changes supabase db diff --schema public supabase db push

Next Steps

After Supabase setup:

  1. Deploy to production - Deploy with Supabase integration
  2. Set up monitoring - Monitor database performance
  3. Configure backups - Ensure data safety
  4. Optimize performance - Tune database queries

This guide ensures ContextWeave has a robust, secure, and scalable database foundation with Supabase.