# Webhook Integration Quick Start

**⏱️ Estimated Time:** 15 minutes

Quick checklist to get Clerk webhooks running in your development environment.

---

## Prerequisites Checklist

- [ ] Clerk account created at [clerk.com](https://clerk.com)
- [ ] Admin app can run locally (`npm run dev`)
- [ ] Database is set up (`packages/database`)
- [ ] Node.js 18+ installed

---

## Step 1: Install Dependencies (2 min)

```bash
cd apps/admin
npm install svix
```

**Verify:**
```bash
npm list svix
# Should show: svix@1.x.x
```

---

## Step 2: Update Database Schema (2 min)

```bash
cd ../../packages/database
npm run db:push
```

**What changed:**
- Password field is now optional (Clerk handles auth)

**Verify:**
```bash
npm run db:studio
# Check users table - password column should allow NULL
```

---

## Step 3: Install Clerk CLI (3 min)

```bash
npm install -g @clerk/clerk-cli
clerk login
```

Follow the browser authentication flow.

**Verify:**
```bash
clerk --version
# Should show version number
```

---

## Step 4: Start Dev Server (1 min)

```bash
cd ../../apps/admin
npm run dev
```

Server should be running at: `http://localhost:3000`

**Keep this terminal open!**

---

## Step 5: Start Webhook Forwarding (2 min)

**Open a NEW terminal window:**

```bash
clerk listen --forward-url http://localhost:3000/api/webhooks
```

**Expected output:**
```
✓ Webhook forwarding is now active!
✓ Webhook secret: whsec_xxxxxxxxxxxxxx

Forwarding webhooks to: http://localhost:3000/api/webhooks
```

**Copy the webhook secret!** You'll need it in the next step.

**Keep this terminal open!**

---

## Step 6: Set Environment Variables (2 min)

Edit `apps/admin/.env.local`:

```env
# Clerk Authentication (should already exist)
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_xxxxx
CLERK_SECRET_KEY=sk_test_xxxxx

# Add this line with the secret from Step 5:
CLERK_WEBHOOK_SECRET=whsec_xxxxxxxxxxxxxx
```

**Restart your dev server** (go back to Terminal 1 and restart with Ctrl+C then `npm run dev`)

---

## Step 7: Test It! (3 min)

### Option A: Sign Up a New User

1. Go to your mobile app or admin app
2. Sign up with a new email
3. Complete email verification

### Option B: Test from Clerk Dashboard

1. Go to [Clerk Dashboard](https://dashboard.clerk.com)
2. Navigate to: Users → Create User
3. Fill in details and save

### Watch the Magic ✨

**In Terminal 1 (dev server):**
```
Received webhook with ID user_abc123 and type user.created
✅ User user_abc123 created in database
```

**In Terminal 2 (clerk CLI):**
```
→ Received event user.created
→ Forwarding to http://localhost:3000/api/webhooks
← Response: 200 OK
```

---

## Verification Checklist

After testing, verify everything works:

- [ ] Both terminals are running without errors
- [ ] You see webhook logs in both terminals
- [ ] User appears in database (check with `npm run db:studio`)
- [ ] User data matches Clerk (email, name)
- [ ] Default role is 'client'

---

## Troubleshooting

### "Error: CLERK_WEBHOOK_SECRET not set"

**Fix:** Add the secret to `.env.local` and restart dev server.

### "Error verifying webhook"

**Fix:** 
1. Copy the EXACT secret from `clerk listen` output
2. Make sure no extra spaces in `.env.local`
3. Restart dev server

### "Webhook not received"

**Fix:**
1. Verify both terminals are running
2. Check dev server is on port 3000
3. Try creating a new user again

### "User not in database"

**Fix:**
1. Check `npm run db:studio` - is database accessible?
2. Did schema migration run? (`npm run db:push`)
3. Check Terminal 1 for SQL errors

---

## What's Next?

✅ **Webhooks Working!** You can now:

1. **Set User Roles:**
   - Go to Clerk Dashboard → Users
   - Select a user
   - Public Metadata: `{"role": "admin"}`
   - Save (will sync to database automatically)

2. **Test Role API:**
   ```bash
   curl -X POST http://localhost:3000/api/admin/set-role \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer YOUR_TOKEN" \
     -d '{"targetUserId": "user_abc", "role": "trainer"}'
   ```

3. **Read Full Documentation:**
   - Setup Guide: `CLERK_WEBHOOK_SETUP.md`
   - Testing Guide: `WEBHOOK_TESTING_GUIDE.md`
   - Integration Summary: `CLERK_WEBHOOK_INTEGRATION_COMPLETE.md`

4. **Move to Production:**
   - See `CLERK_WEBHOOK_SETUP.md` → Production section
   - Configure endpoint in Clerk Dashboard
   - Deploy with production webhook secret

---

## Common Commands Reference

```bash
# Start dev server
cd apps/admin && npm run dev

# Start webhook forwarding
clerk listen --forward-url http://localhost:3000/api/webhooks

# View database
cd packages/database && npm run db:studio

# Update database schema
cd packages/database && npm run db:push

# Check logs
# Just watch Terminal 1 (dev server) and Terminal 2 (clerk CLI)
```

---

## Production Deployment Quick Steps

When you're ready to deploy:

1. **Clerk Dashboard:**
   - Webhooks → Add Endpoint
   - URL: `https://yourdomain.com/api/webhooks`
   - Subscribe to: `user.created`, `user.updated`, `user.deleted`
   - Copy signing secret

2. **Production Environment:**
   ```env
   CLERK_WEBHOOK_SECRET=whsec_prod_xxxxxx
   ```

3. **Test:**
   - Send test event from Clerk Dashboard
   - Verify 200 response
   - Check production database

---

## Support

- **Detailed Setup:** `CLERK_WEBHOOK_SETUP.md`
- **Testing Guide:** `WEBHOOK_TESTING_GUIDE.md`
- **Troubleshooting:** Both guides above + `TROUBLESHOOTING.md`
- **Clerk Docs:** https://clerk.com/docs/integrations/webhooks

---

**That's it! You're done.** 🎉

Webhooks are now syncing Clerk users to your database automatically.