# Client-Side to Server-Side Migration Guide

## ✅ Completed Infrastructure

### Server-Side Utilities
- ✅ `utils/serverApiClient.ts` - Server-side API client with token management
- ✅ `utils/apiRouteHandler.ts` - API route wrapper with auth proxy
- ✅ `utils/staticValues.ts` - Updated with public/private separation

### API Routes Created
- ✅ Authentication: `/api/auth/login`, `/api/auth/register`, `/api/auth/logout`
- ✅ Cart: `/api/cart/list`, `/api/cart/add`, `/api/cart/update`, `/api/cart/remove`
- ✅ Wishlist: `/api/wishlist/list`, `/api/wishlist/add`, `/api/wishlist/remove`
- ✅ Checkout: `/api/checkout`
- ✅ User: `/api/user/profile`, `/api/user/orders`
- ✅ Co-Creation: `/api/co-creation/save`
- ✅ Coupon: `/api/coupon/apply`

### Security Updates
- ✅ proxy updated to protect API routes and pages
- ✅ HTTP-only cookies for token storage
- ✅ Environment variable separation

## 📝 How to Update Client Components

### Before (Client-Side - Insecure ❌)
```typescript
"use client";
import Cookies from "js-cookie";
import { API_BASE_URL } from "@/utils/staticValues";

export default function CartPage() {
  const [cart, setCart] = useState([]);

  async function fetchCart() {
    const response = await fetch(`${API_BASE_URL}/cart/list`, {
      headers: {
        Authorization: `Bearer ${Cookies.get("token")}`, // Token exposed!
      },
    });
    const data = await response.json();
    setCart(data.data);
  }

  async function addToCart(productId: string) {
    await fetch(`${API_BASE_URL}/cart/save`, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${Cookies.get("token")}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ product_id: productId }),
    });
  }
}
```

### After (Server-Side via API Routes - Secure ✅)
```typescript
"use client";
// No more direct API calls or token handling!

export default function CartPage() {
  const [cart, setCart] = useState([]);

  async function fetchCart() {
    // Call Next.js API route - token handled server-side
    const response = await fetch('/api/cart/list');
    const data = await response.json();
    
    if (data.success) {
      setCart(data.data);
    }
  }

  async function addToCart(productId: string) {
    const response = await fetch('/api/cart/add', {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ product_id: productId }),
    });
    
    const data = await response.json();
    if (data.success) {
      await fetchCart(); // Refresh cart
    }
  }
}
```

## 🔄 Migration Checklist for Each Component

### 1. Login Component
- ✅ Update to use `/api/auth/login`
- ✅ Remove `Cookies.set()` calls
- ✅ Handle response and redirect

### 2. Cart Components
- [ ] Update `app/bag/page.tsx` to use `/api/cart/*`
- [ ] Remove all `API_BASE_URL` imports
- [ ] Remove all `Cookies.get("token")` calls

### 3. Wishlist Components
- [ ] Update wishlist buttons to use `/api/wishlist/*`

### 4. Checkout Flow
- [ ] Update payment flow to use `/api/checkout`

### 5. Dashboard
- [ ] Update user profile to use `/api/user/profile`
- [ ] Update order history to use `/api/user/orders`

## 🛡️ Security Benefits

1. **Token Protection**: Tokens stored in HTTP-only cookies, inaccessible to JavaScript
2. **API Key Security**: Backend URL never exposed to client
3. **CSRF Protection**: Built-in Next.js protection
4. **XSS Protection**: HTTP-only cookies prevent token theft
5. **No Client-Side Secrets**: All sensitive data stays on server

## 📋 Next Steps

1. Test authentication flow with new API routes
2. Update client components one by one
3. Remove unused `apiClient.tsx` after migration
4. Add rate limiting to API routes
5. Add logging for security events
6. Set up monitoring for failed auth attempts

## 🧪 Testing

```bash
# Test login
curl -X POST http://localhost:3000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"test@example.com","password":"password"}'

# Test protected route (should fail without cookie)
curl http://localhost:3000/api/cart/list

# Test logout
curl -X POST http://localhost:3000/api/auth/logout \
  -H "Cookie: token=YOUR_TOKEN_HERE"
```
