# 🚀 Panduan Setup Supabase dari Awal (Untuk Pemula)

**Tanggal:** August 14, 2026  
**Durasi:** ~30-45 menit  
**Level:** Pemula  
**Target:** Setup database untuk EcoLearn

---

## 📋 Apa itu Supabase?

Supabase adalah **backend-as-a-service** yang menyediakan:
- 🗄️ Database PostgreSQL (untuk menyimpan data)
- 🔐 Authentication (untuk login/register)
- 🛡️ Security (Row Level Security untuk proteksi data)
- 🚀 Real-time APIs (REST API siap pakai)

Singkatnya: Kita tidak perlu setup server sendiri, semuanya sudah siap di cloud Supabase.

---

## 🎯 Step 1: Membuat Akun Supabase

### 1.1 Buka Website Supabase

Buka browser Anda dan kunjungi:
```
https://supabase.com
```

**Apa yang Anda lihat:**
- Hero section dengan tulisan "The Open Source Firebase Alternative"
- Tombol "Start your project" atau "Sign Up"

### 1.2 Klik "Sign Up" atau "Start your project"

![Akan membawa ke halaman signup]

**Pilihan login:**
- Email + Password
- GitHub
- Google

**Rekomendasi:** Gunakan GitHub (lebih cepat, sudah terintegrasi)

### 1.3 Isi Data Signup

Jika pilih Email + Password:
```
Email:     your-email@gmail.com
Password:  [gunakan password yang kuat]
           (simpan di tempat aman!)
```

**Setelah submit:**
- Verifikasi email (cek inbox Anda)
- Klik link verifikasi dari Supabase
- Dashboard siap digunakan

---

## 🏗️ Step 2: Membuat Project Supabase

### 2.1 Buka Dashboard Supabase

Setelah login, Anda akan masuk ke **Supabase Dashboard**.

**Apa yang Anda lihat:**
```
┌────────────────────────────────────┐
│     Supabase Dashboard             │
├────────────────────────────────────┤
│ [New Project] [Teams] [Settings]   │
│                                    │
│ Projects:                          │
│ (Kosong - belum ada project)       │
└────────────────────────────────────┘
```

### 2.2 Klik Tombol "New Project"

**Form yang muncul:**

```
Organization: [pilih atau buat baru]
  ↓ Default: "personal"

Project Name: *
  ↓ Input: ecolearn_db  (atau nama yang Anda inginkan)
  
Database Password: * (auto-generated, simpan dengan aman!)
  ↓ Salin password ini untuk nanti!

Region: 
  ↓ Pilih: Singapore (asia-southeast1)
     atau terdekat dengan lokasi Anda
     (untuk kecepatan akses)

Pricing Plan:
  ↓ Pilih: Free Tier (gratis untuk development)
```

### 2.3 Klik "Create new project"

**Tunggu Loading (~2-3 menit)**

Supabase sedang:
- ✓ Provision server
- ✓ Setup database
- ✓ Create authentication system
- ✓ Setup API endpoints

Akan ada loading bar atau indikator progress.

### 2.4 Project Siap!

Setelah selesai, Anda akan masuk ke **Project Dashboard**.

**Apa yang Anda lihat:**

```
┌─────────────────────────────────────────────────┐
│ Project: ecolearn_db                            │
├─────────────────────────────────────────────────┤
│                                                 │
│ Left Sidebar:                                   │
│ • Project Settings                              │
│ • API                                           │
│ • Database                                      │
│ • Authentication                                │
│ • SQL Editor                                    │
│                                                 │
│ Main Area:                                      │
│ [Welcome to Supabase!]                          │
│ [Beberapa quick start guides]                   │
│                                                 │
└─────────────────────────────────────────────────┘
```

---

## 🔑 Step 3: Mendapatkan API Keys

API Keys diperlukan untuk menghubungkan app Next.js dengan database Supabase.

### 3.1 Buka "Project Settings"

Di **Left Sidebar**, klik:
```
⚙️ Project Settings  (atau cari icon settings)
```

**Menu yang terbuka:**
```
API
├─ Project URL
├─ Project API Keys
│  └─ anon key (public, boleh di-share)
│  └─ service_role key (rahasia, jangan di-share)
└─ Configuration
```

### 3.2 Cari "API" atau "Keys"

Klik tab **"API"** untuk melihat credentials:

```
┌─────────────────────────────────────────────┐
│ Project API Settings                        │
├─────────────────────────────────────────────┤
│                                             │
│ Project URL:                                │
│ https://xxxxxxxxxxxx.supabase.co           │
│ [Copy button] ← Salin ini                   │
│                                             │
│ Project API Keys:                           │
│                                             │
│ › anon key                                  │
│   eyJhbGciOiJIUzI1NiIsInR5... (long string)│
│   [Copy button] ← Salin ini                 │
│                                             │
│ › service_role key                          │
│   eyJhbGciOiJIUzI1NiIsInR5... (long string)│
│   [Copy button] ← Salin ini (HATI-HATI!)   │
│                                             │
└─────────────────────────────────────────────┘
```

### 3.3 Salin 3 Credentials Penting

**Simpan di notepad sementara:**

```
NEXT_PUBLIC_SUPABASE_URL = https://xxxxxxxxxxxx.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY = eyJhbGciOiJIUzI1NiIsInR5...
SUPABASE_SERVICE_ROLE_KEY = eyJhbGciOiJIUzI1NiIsInR5...
```

**⚠️ PENTING:**
- Jangan share credentials ke public
- Jangan commit ke GitHub
- Anon key: boleh di-client side (di `.env.local`)
- Service role key: RAHASIA, hanya di server (di `.env.local` juga untuk dev)

---

## 📊 Step 4: Setup Database Schema

### 4.1 Buka SQL Editor

Di **Left Sidebar**, klik:
```
SQL Editor  (atau icon <>)
```

**Yang muncul:**
- Editor text untuk menulis SQL queries
- Tombol "Run" atau "Execute"
- History queries

### 4.2 Jalankan SQL Schema

**Di SQL Editor:**

1. Klik "New Query"
2. Copy-paste SQL schema dari file `SCHEMA.md`
3. Tekan tombol **"Run"** atau **Ctrl+Enter**

**Struktur SQL yang akan dijalankan:**

```sql
-- 1. Create tables
CREATE TABLE profiles ( ... );
CREATE TABLE videos ( ... );
CREATE TABLE game_sessions ( ... );
-- ... lebih banyak tables

-- 2. Create indexes (untuk performance)
CREATE INDEX idx_profiles_username ON profiles(username);
-- ... lebih banyak indexes

-- 3. Create functions (untuk business logic)
CREATE OR REPLACE FUNCTION handle_daily_login(...) { ... };
-- ... lebih banyak functions

-- 4. Create triggers (untuk automation)
CREATE TRIGGER on_auth_user_created AFTER INSERT ON auth.users ...;
-- ... lebih banyak triggers
```

**Apa yang terjadi:**
- ✓ Database tables terbuat
- ✓ Relationships antar tabel terbentuk
- ✓ Indexes dibuat untuk cepat
- ✓ Functions siap digunakan

### 4.3 Verifikasi Schema Sudah Ada

**Di Left Sidebar**, klik:
```
Database → Tables
```

**Akan muncul daftar tabel:**
```
✓ profiles
✓ videos
✓ video_progress
✓ quizzes
✓ quiz_questions
✓ quiz_options
✓ quiz_attempts
✓ quiz_answers
✓ game_sessions
✓ badges
✓ user_badges
✓ learning_modules
✓ learning_progress
```

✅ **Jika semua tabel ada, schema berhasil!**

---

## 🔐 Step 5: Setup Row Level Security (RLS)

RLS = Keamanan untuk membatasi data. Contoh:
- User A hanya bisa lihat data user A
- User A tidak bisa lihat data user B
- Admin bisa lihat semua

### 5.1 Jalankan SQL Policies

**Di SQL Editor**, jalankan queries RLS dari `SCHEMA.md`:

```sql
-- Enable RLS pada tables
ALTER TABLE profiles ENABLE ROW LEVEL SECURITY;
ALTER TABLE game_sessions ENABLE ROW LEVEL SECURITY;
ALTER TABLE quiz_attempts ENABLE ROW LEVEL SECURITY;
-- ... lebih banyak

-- Create policies
CREATE POLICY "Users can read own profile" ON profiles ...;
CREATE POLICY "Users can insert own game sessions" ON game_sessions ...;
-- ... lebih banyak policies
```

### 5.2 Verifikasi RLS Aktif

**Di sidebar**, klik:
```
Database → Tables → profiles
```

**Buka tab "Security":**
```
RLS: [Enabled] ✓
Policies:
  - Users can read own profile
  - Users can update own profile
  - ... etc
```

✅ **Jika RLS enabled, security setup berhasil!**

---

## 🧪 Step 6: Test Authentication Setup

Authentication sudah built-in di Supabase. Kita test di SQL Editor.

### 6.1 Buka SQL Editor

Jalankan query untuk membuat test user:

```sql
-- Create test user (manual, untuk development saja)
INSERT INTO auth.users (id, email, email_confirmed_at, encrypted_password, raw_user_meta_data, created_at, updated_at)
VALUES (
  gen_random_uuid(),
  'test@example.com',
  now(),
  crypt('password123', gen_salt('bf')),
  '{"provider": "email"}',
  now(),
  now()
);
```

**Atau lebih mudah, test di Next.js nanti dengan signup form** ✓

---

## 🔗 Step 7: Connect dengan Next.js App

Sekarang hubungkan Supabase ke Next.js app Anda.

### 7.1 Update `.env.local`

**File:** `Website-Pemilahan-Sampah/.env.local`

Ganti placeholder dengan credentials yang Anda copy tadi:

```dotenv
# Supabase Configuration
NEXT_PUBLIC_SUPABASE_URL=https://xxxxxxxxxxxx.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5...
SUPABASE_SERVICE_ROLE_KEY=eyJhbGciOiJIUzI1NiIsInR5...

# Application
NEXT_PUBLIC_APP_URL=http://localhost:3000
NODE_ENV=development
```

**⚠️ Contoh format yang benar:**
```
NEXT_PUBLIC_SUPABASE_URL=https://aaabbbcccdddeeefffggg.supabase.co
                         (copy full URL dari Supabase)

NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
                              (copy full string, bisa panjang)
```

### 7.2 Restart Next.js Server

**Terminal:**

```bash
# Jika sudah running, stop dengan Ctrl+C
# Kemudian jalankan ulang
npm run dev

# Output akan terlihat:
# ▲ Next.js 14.x.x
# ✓ Ready in 1.2s
# ✓ Listening on http://localhost:3000
```

### 7.3 Test Koneksi

Buka browser:
```
http://localhost:3000
```

**Jika tidak ada error:** ✅ Koneksi berhasil!

**Jika ada error:**
```
Error: Missing Supabase environment variables
```

Periksa:
1. File `.env.local` sudah update?
2. Nilai credentials sudah paste dengan benar?
3. Sudah restart server?

---

## 🧬 Step 8: Seed Data (Optional)

Ini untuk menambahkan data sampel (video, badges, dll).

### 8.1 Buka SQL Editor

Jalankan insert queries dari `SCHEMA.md` bagian "Seeding Sample Data":

```sql
-- Insert sample badges
INSERT INTO badges (slug, title, description, badge_category, achievement_type) VALUES
('eco_scholar', 'Eco Scholar', 'Selesaikan Modul 1', 'learning', 'module_completion'),
('waste_master', 'Waste Master', 'Selesaikan Modul 2', 'learning', 'module_completion'),
-- ... dst
```

```sql
-- Insert sample videos
INSERT INTO videos (title, slug, description, video_url, duration_seconds) VALUES
('Pengenalan Sampah', 'intro-waste', 'Video pengenalan...', 'https://youtube.com/...', 600),
-- ... dst
```

### 8.2 Verifikasi Data Masuk

**Di sidebar**, klik:
```
Database → Tables → badges
```

**Tab "Data" akan menampilkan:**
```
✓ eco_scholar
✓ waste_master
✓ sustainability_expert
✓ ... dst
```

---

## 📱 Step 9: Test Signup/Login

### 9.1 Buka App di Browser

```
http://localhost:3000
```

### 9.2 Klik "Sign Up"

Isi form:
```
Email:    your-test-email@gmail.com
Password: testpassword123
```

Klik **"Daftar"**

**Apa yang terjadi:**
- Supabase membuat record baru di `auth.users`
- Trigger `handle_new_user()` membuat profile otomatis
- Email verifikasi dikirim (cek inbox)

### 9.3 Test Login

Logout, kemudian klik "Login"

Isi:
```
Email:    your-test-email@gmail.com
Password: testpassword123
```

Klik **"Login"**

**Jika berhasil:** ✅ Auth system bekerja!

---

## 🐛 Troubleshooting

### Error 1: "Missing Supabase environment variables"

**Penyebab:** `.env.local` belum update atau salah format

**Solusi:**
1. Buka `Website-Pemilahan-Sampah/.env.local`
2. Pastikan ada 3 baris:
   ```
   NEXT_PUBLIC_SUPABASE_URL=...
   NEXT_PUBLIC_SUPABASE_ANON_KEY=...
   SUPABASE_SERVICE_ROLE_KEY=...
   ```
3. Restart server: `npm run dev`

### Error 2: "Database error" saat signup

**Penyebab:** Schema belum dijalankan atau ada syntax error

**Solusi:**
1. Buka Supabase dashboard
2. SQL Editor → New Query
3. Cek apakah semua tables ada: `SELECT * FROM information_schema.tables;`
4. Jika belum, jalankan ulang schema SQL

### Error 3: "Connection refused"

**Penyebab:** Supabase project belum aktif atau credentials salah

**Solusi:**
1. Buka Supabase dashboard
2. Cek project status (harus "Active")
3. Verifikasi URL dan keys lagi
4. Restart Next.js: `npm run dev`

### Error 4: "CORS error"

**Penyebab:** Supabase project belum whitelist localhost

**Solusi:**
1. Supabase Dashboard → Project Settings → API
2. Cari "CORS" atau "Allowed Origins"
3. Tambahkan: `http://localhost:3000`
4. Save

---

## ✅ Checklist Setup Selesai

Sebelum melanjutkan ke Week 2, pastikan:

- [ ] Account Supabase sudah dibuat
- [ ] Project `ecolearn_db` sudah dibuat
- [ ] API credentials sudah tercopy
- [ ] `.env.local` sudah diupdate
- [ ] Schema SQL sudah dijalankan
- [ ] RLS policies sudah dijalankan
- [ ] Tables muncul di Supabase dashboard
- [ ] Next.js server restart dan tidak ada error
- [ ] Signup/Login test berhasil
- [ ] Data user muncul di `profiles` table

---

## 📚 Referensi Lanjutan

**Dokumentasi resmi:**
- Supabase Docs: https://supabase.com/docs
- Auth Guide: https://supabase.com/docs/guides/auth/overview
- Database: https://supabase.com/docs/guides/database/overview
- Security: https://supabase.com/docs/guides/security/row-level-security

**Video Tutorials:**
- Supabase Playlist: https://www.youtube.com/playlist?list=PLdYNUzF-zAWZ-bLDrHxXZPCq2A8xZlH-I

---

## 🎉 Selesai!

Anda sudah selesai setup Supabase untuk development! 

**Next Steps (Week 2):**
1. Implement API endpoints (`/api/games`, `/api/quiz`, dll)
2. Connect game logic ke database
3. Implement leaderboard
4. Test seluruh flow

**Pertanyaan?** Hubungi team development atau lihat docs di atas.

---

**Last Updated:** August 14, 2026  
**Version:** 1.0.0
