Skip to content

Latest commit

Β 

History

History
473 lines (362 loc) Β· 10.4 KB

File metadata and controls

473 lines (362 loc) Β· 10.4 KB

πŸš€ Supabase + Vercel Migration Guide

City Service Provider Application

πŸ“‹ Overview

This guide provides step-by-step instructions for migrating the City Service Provider Application from Spring Boot + PostgreSQL to Supabase + Vercel.


🎯 Migration Benefits

βœ… What You Gain

  • Serverless Architecture: No server management required
  • Real-time Features: Built-in real-time subscriptions
  • Automatic Scaling: Handles traffic spikes automatically
  • Global CDN: Fast content delivery worldwide
  • Integrated Auth: Built-in authentication with social providers
  • File Storage: Integrated file storage with CDN
  • Cost Effective: Pay only for what you use
  • Developer Experience: Modern tooling and workflows

πŸ“Š Architecture Comparison

Component Before (Spring Boot) After (Supabase + Vercel)
Backend Java Spring Boot Supabase Edge Functions (TypeScript)
Database PostgreSQL Supabase PostgreSQL
Authentication Custom JWT Supabase Auth
File Storage Local/S3 Supabase Storage
Frontend Hosting Manual Vercel (Automatic)
Real-time Manual WebSocket Supabase Real-time
API REST REST + GraphQL + Real-time

πŸ› οΈ Prerequisites

Required Tools

# Node.js (v16 or later)
node --version

# npm or yarn
npm --version

# Supabase CLI
npm install -g supabase

# Vercel CLI
npm install -g vercel

# Git
git --version

Accounts Needed


πŸš€ Quick Start (Automated)

Option 1: One-Command Deployment

# Run the automated deployment script
./deploy-supabase-vercel.sh

Option 2: Step-by-Step Manual Setup

Follow the detailed instructions below for manual setup and customization.


πŸ“‹ Step-by-Step Migration

Step 1: Supabase Project Setup

1.1 Create Supabase Project

# Login to Supabase
supabase login

# Create new project (or use existing)
supabase projects create city-service-app

# Initialize local project
supabase init

1.2 Configure Database Schema

# Start local Supabase
supabase start

# Run initial migration
supabase db reset

# Apply custom schema
supabase db push

1.3 Load Sample Data

-- Run in Supabase SQL Editor or locally
-- File: migration/data-migration.sql

Step 2: Edge Functions Deployment

2.1 Deploy Authentication Functions

supabase functions deploy auth-helpers

2.2 Deploy Provider Functions

supabase functions deploy providers

2.3 Deploy Service Functions

supabase functions deploy services

Step 3: Frontend Migration

3.1 Install Supabase Dependencies

cd frontend
npm install @supabase/supabase-js @supabase/auth-helpers-react

3.2 Configure Environment Variables

# Copy environment template
cp env.supabase.example .env.local

# Update with your Supabase credentials
# REACT_APP_SUPABASE_URL=https://your-project.supabase.co
# REACT_APP_SUPABASE_ANON_KEY=your-anon-key

3.3 Update Service Files

The following files have been created/updated for Supabase integration:

  • src/lib/supabase.js - Supabase client configuration
  • src/services/supabaseAuthService.js - Authentication service
  • src/services/supabaseProviderService.js - Provider service
  • src/services/supabaseServiceService.js - Service management

Step 4: Vercel Deployment

4.1 Connect to Vercel

# Login to Vercel
vercel login

# Link project
vercel link

# Set environment variables
vercel env add REACT_APP_SUPABASE_URL
vercel env add REACT_APP_SUPABASE_ANON_KEY

4.2 Deploy to Production

# Deploy to production
vercel --prod

πŸ”§ Configuration Details

Database Configuration

Row Level Security (RLS) Policies

-- Example: Users can only view their own profile
CREATE POLICY "Users can view own profile" ON user_profiles
  FOR SELECT USING (auth.uid() = id);

-- Example: Anyone can view active providers
CREATE POLICY "Anyone can view active providers" ON service_providers
  FOR SELECT USING (is_available = true);

Storage Buckets

-- Create storage buckets
INSERT INTO storage.buckets (id, name, public) VALUES 
  ('profile-images', 'profile-images', true),
  ('service-images', 'service-images', true);

Authentication Configuration

Email Templates

Configure in Supabase Dashboard > Authentication > Email Templates:

  • Confirmation email
  • Password reset email
  • Magic link email

Social Providers

Enable in Supabase Dashboard > Authentication > Providers:

  • Google OAuth
  • Facebook OAuth
  • GitHub OAuth

Real-time Configuration

Enable Real-time

// Subscribe to provider updates
const subscription = supabase
  .channel('providers')
  .on('postgres_changes', 
    { event: '*', schema: 'public', table: 'service_providers' },
    (payload) => {
      console.log('Provider updated:', payload)
    }
  )
  .subscribe()

πŸ§ͺ Testing

Local Testing

# Start local Supabase
supabase start

# Start frontend development server
cd frontend
npm start

# Run tests
npm test

Production Testing

# Test Edge Functions
curl -X GET "https://your-project.supabase.co/functions/v1/providers"

# Test frontend
curl -X GET "https://your-app.vercel.app"

πŸ“Š Monitoring & Analytics

Supabase Dashboard

  • Database performance
  • API usage
  • Authentication metrics
  • Storage usage

Vercel Analytics

  • Page views
  • Performance metrics
  • Error tracking
  • Deployment logs

Custom Monitoring

// Error tracking
window.addEventListener('error', (event) => {
  // Send to monitoring service
  console.error('Application error:', event.error)
})

// Performance monitoring
const observer = new PerformanceObserver((list) => {
  // Track performance metrics
})
observer.observe({ entryTypes: ['navigation', 'paint'] })

πŸ”’ Security Best Practices

Database Security

  • βœ… Enable Row Level Security on all tables
  • βœ… Use proper authentication checks
  • βœ… Validate input data
  • βœ… Use prepared statements (automatic with Supabase)

API Security

  • βœ… Implement rate limiting
  • βœ… Validate JWT tokens
  • βœ… Use HTTPS only
  • βœ… Sanitize user input

Frontend Security

  • βœ… Store tokens securely
  • βœ… Implement CSP headers
  • βœ… Validate user permissions
  • βœ… Use environment variables for secrets

🚨 Troubleshooting

Common Issues

1. Authentication Errors

# Check Supabase connection
supabase status

# Verify environment variables
echo $REACT_APP_SUPABASE_URL
echo $REACT_APP_SUPABASE_ANON_KEY

2. Database Connection Issues

-- Check RLS policies
SELECT * FROM pg_policies WHERE tablename = 'user_profiles';

-- Verify user permissions
SELECT auth.uid(), auth.role();

3. Edge Function Errors

# Check function logs
supabase functions logs auth-helpers

# Deploy with verbose output
supabase functions deploy providers --debug

4. Vercel Deployment Issues

# Check build logs
vercel logs

# Verify environment variables
vercel env ls

Debug Mode

# Enable debug mode in frontend
REACT_APP_DEBUG=true npm start

# Enable Supabase debug mode
supabase start --debug

πŸ“ˆ Performance Optimization

Database Optimization

-- Add indexes for frequently queried columns
CREATE INDEX idx_providers_rating ON service_providers(average_rating DESC);
CREATE INDEX idx_services_category ON services(category_id);
CREATE INDEX idx_bookings_user ON bookings(user_id);

Frontend Optimization

// Lazy load components
const ProviderDetail = lazy(() => import('./ProviderDetail'))

// Optimize images
const optimizedImageUrl = supabase.storage
  .from('profile-images')
  .getPublicUrl('image.jpg', {
    transform: {
      width: 300,
      height: 300,
      quality: 80
    }
  })

Caching Strategy

// Cache frequently accessed data
const cachedProviders = useMemo(() => {
  return providers.filter(p => p.is_featured)
}, [providers])

// Use React Query for server state
const { data: providers } = useQuery(
  'providers',
  () => providerService.getProviders(),
  { staleTime: 5 * 60 * 1000 } // 5 minutes
)

πŸ”„ Migration Rollback Plan

Emergency Rollback

If issues arise, you can quickly rollback:

  1. DNS Revert: Point domain back to original server
  2. Database Restore: Restore from pre-migration backup
  3. Code Revert: Revert to previous Git commit
  4. Service Restart: Restart original Spring Boot application

Partial Rollback

  • Use feature flags to disable new features
  • Route specific endpoints to old backend
  • Gradual migration of user segments

πŸ“š Additional Resources

Documentation

Tutorials

Community


πŸŽ‰ Success Metrics

Technical Metrics

  • βœ… 99.9% uptime
  • βœ… < 200ms API response time
  • βœ… < 2s page load time
  • βœ… Zero security vulnerabilities

Business Metrics

  • βœ… Reduced hosting costs by 60%
  • βœ… Improved developer productivity
  • βœ… Faster feature deployment
  • βœ… Better user experience

πŸ“ž Support

Getting Help

  1. Check Documentation: Review this guide and official docs
  2. Search Issues: Look for similar problems in GitHub issues
  3. Community Support: Ask in Discord or forums
  4. Professional Support: Contact Supabase/Vercel support

Reporting Issues

When reporting issues, include:

  • Error messages and logs
  • Steps to reproduce
  • Environment details
  • Expected vs actual behavior

🎊 Congratulations! You've successfully migrated to a modern, scalable architecture with Supabase and Vercel. Your application is now ready for the future with real-time features, automatic scaling, and a great developer experience.