Skip to content

Latest commit

 

History

History
355 lines (273 loc) · 8.39 KB

File metadata and controls

355 lines (273 loc) · 8.39 KB

🚀 Supabase Backend Setup Guide

📋 Overview

This guide will help you set up the complete backend for your AI Portfolio using Supabase.


🎯 Step 1: Create Supabase Account

  1. Go to https://supabase.com
  2. Click "Start your project"
  3. Sign up with GitHub (recommended) or email
  4. Create a new organization (free tier is perfect)

🏗️ Step 2: Create New Project

  1. Click "New Project"
  2. Fill in the details:
    • Project Name: ai-portfolio (or your choice)
    • Database Password: Create a strong password (save it!)
    • Region: Choose closest to your target audience
    • Pricing Plan: Free (includes 500MB database, 50MB file storage)
  3. Click "Create new project"
  4. Wait 2-3 minutes for setup to complete

🗄️ Step 3: Set Up Database Tables

  1. In your Supabase dashboard, go to SQL Editor (left sidebar)
  2. Click "New query"
  3. Open the file supabase-setup.sql from your project
  4. Copy ALL the SQL code
  5. Paste it into the SQL Editor
  6. Click "Run" (or press Ctrl+Enter)
  7. You should see success messages

✅ What This Creates:

5 Tables:

  • visitor_sessions - Track visitor sessions
  • page_views - Track page views
  • chat_messages - Store all chat conversations
  • contact_submissions - Store contact form data
  • user_interactions - Track user actions (clicks, etc.)

4 Analytics Views:

  • daily_visitors - Daily visitor statistics
  • popular_questions - Most asked questions
  • contact_summary - Contact form summary
  • interaction_summary - User interaction summary

2 Functions:

  • get_chat_statistics() - Get chat stats
  • cleanup_old_data() - Clean old records

🔑 Step 4: Get API Keys

  1. Go to SettingsAPI (in left sidebar)
  2. You'll see two important values:

Project URL

https://xxxxxxxxxxxxx.supabase.co

API Keys

  • anon/public key (safe to use in frontend)
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

⚠️ Important:

  • ✅ USE the anon/public key in your frontend
  • ❌ NEVER use the service_role key in frontend
  • The service_role key bypasses all security

⚙️ Step 5: Update Configuration

  1. Open config.js in your project
  2. Replace the placeholder values:
const SUPABASE_CONFIG = {
    url: 'https://xxxxxxxxxxxxx.supabase.co', // Your Project URL
    anonKey: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...' // Your anon/public key
};
  1. Save the file

🧪 Step 6: Test the Integration

  1. Open index.html in your browser
  2. Open browser console (F12)
  3. You should see: ✅ Supabase connected successfully
  4. Try chatting with the AI
  5. Check your Supabase dashboard → Table Editor
  6. You should see new records in:
    • visitor_sessions
    • chat_messages
    • user_interactions

📊 Step 7: View Your Analytics

Using Table Editor

  1. Go to Table Editor in Supabase dashboard
  2. Select any table to view data
  3. Use filters and search

Using SQL Editor

Run these queries to see analytics:

-- Recent chat messages
SELECT * FROM chat_messages 
ORDER BY timestamp DESC 
LIMIT 20;

-- Daily visitors
SELECT * FROM daily_visitors 
LIMIT 30;

-- Popular questions
SELECT * FROM popular_questions;

-- Chat statistics
SELECT * FROM get_chat_statistics();

-- Recent contact submissions
SELECT name, email, message, submitted_at 
FROM contact_submissions 
ORDER BY submitted_at DESC;

🎨 What Data is Being Tracked

1. Visitor Sessions

  • Unique visitor ID (stored in localStorage)
  • Session ID for each visit
  • User agent (browser info)
  • Screen resolution
  • Referrer (how they found you)
  • Landing page

2. Chat Messages

  • User questions
  • AI responses
  • Timestamps
  • Session info

3. User Interactions

  • Theme toggles
  • Social link clicks
  • Suggestion button clicks
  • Chat cleared events

4. Page Views

  • Which pages visitors view
  • Time spent on each page

5. Contact Form

  • Name, email, message
  • Submission timestamp
  • Status tracking (new/read/replied)

🔒 Security (Row Level Security)

All tables have RLS enabled:

  • ✅ Anyone can INSERT (submit data)
  • ✅ Only authenticated users (you) can READ
  • ✅ Public data is protected
  • ✅ No one can delete data from the frontend

To access your data:

  1. Go to Supabase Dashboard
  2. View tables in Table Editor
  3. Run queries in SQL Editor

📈 Additional APIs You Can Add

1. Newsletter Subscription

CREATE TABLE newsletter_subscribers (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    email TEXT UNIQUE NOT NULL,
    name TEXT,
    subscribed_at TIMESTAMP DEFAULT NOW(),
    status TEXT DEFAULT 'active'
);

2. Project Reactions (Like/Love projects)

CREATE TABLE project_reactions (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    visitor_id TEXT NOT NULL,
    project_name TEXT NOT NULL,
    reaction_type TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT NOW()
);

3. Blog Comments (if you add a blog)

CREATE TABLE blog_comments (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    post_id TEXT NOT NULL,
    visitor_id TEXT,
    name TEXT NOT NULL,
    email TEXT,
    comment TEXT NOT NULL,
    approved BOOLEAN DEFAULT false,
    created_at TIMESTAMP DEFAULT NOW()
);

4. Feedback/Ratings

CREATE TABLE site_feedback (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    visitor_id TEXT,
    rating INTEGER CHECK (rating >= 1 AND rating <= 5),
    feedback TEXT,
    page_url TEXT,
    created_at TIMESTAMP DEFAULT NOW()
);

5. AI Chat Feedback (thumbs up/down on responses)

CREATE TABLE chat_feedback (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    message_id UUID REFERENCES chat_messages(id),
    visitor_id TEXT NOT NULL,
    helpful BOOLEAN NOT NULL,
    feedback_text TEXT,
    created_at TIMESTAMP DEFAULT NOW()
);

🚀 Advanced Features You Can Build

1. Email Notifications (using Supabase Edge Functions)

  • Get notified when someone submits contact form
  • Daily analytics summary emails

2. Realtime Chat

  • Use Supabase Realtime for live updates
  • See visitors typing in real-time

3. Admin Dashboard

  • Create a separate admin page to view analytics
  • Respond to contact submissions
  • Monitor chat conversations

4. AI Training

  • Export chat data to improve AI responses
  • Identify common questions
  • Add new knowledge base entries

5. A/B Testing

  • Track which UI variations perform better
  • Test different AI responses

🔧 Maintenance

Weekly Tasks:

  • Review contact submissions
  • Check popular questions
  • Monitor visitor trends

Monthly Tasks:

  • Clean old data (optional):
SELECT cleanup_old_data(90); -- Keep last 90 days

🆘 Troubleshooting

Issue: "Supabase not configured"

  • Check if config.js is loaded before script.js
  • Verify URL and API key are correct
  • Make sure there are no spaces in the keys

Issue: "Insert failed"

  • Check RLS policies in Supabase dashboard
  • Verify table names match exactly
  • Check browser console for detailed errors

Issue: No data showing in tables

  • Open browser console (F12)
  • Look for error messages
  • Verify Supabase connection message appears

Issue: CORS errors

  • Supabase handles CORS automatically
  • Make sure you're using the anon key, not service_role

📞 Support Resources


✅ Checklist

  • Created Supabase account
  • Created new project
  • Ran SQL setup script
  • Got API keys
  • Updated config.js
  • Tested in browser
  • Verified data in tables
  • Checked browser console for errors
  • Reviewed analytics views

🎉 You're All Set!

Your AI portfolio now has a complete backend with:

  • ✅ Visitor tracking
  • ✅ Chat history storage
  • ✅ Contact form database
  • ✅ Analytics and insights
  • ✅ User interaction tracking

Start promoting your portfolio and watch the data flow in! 🚀