# 🚀 Quick Reference: Client to Server Migration

## Before vs After

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

// Login
const response = await fetch(`${API_BASE_URL}/login`, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ email, password }),
});
const data = await response.json();
Cookies.set("token", data.access_token); // ❌ Token exposed!

// Authenticated Request
const cart = await fetch(`${API_BASE_URL}/cart/list`, {
  headers: {
    Authorization: `Bearer ${Cookies.get("token")}`, // ❌ Token in JavaScript!
  },
});
```

### ✅ NEW WAY (Server-Side - Secure)
```typescript
// Login - No token handling needed!
const response = await fetch('/api/auth/login', {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ email, password }),
});
const data = await response.json();
// ✅ Token automatically stored in HTTP-only cookie server-side

// Authenticated Request - Token sent automatically!
const response = await fetch('/api/cart/list');
const data = await response.json();
// ✅ Token included automatically from HTTP-only cookie
```

## API Routes Available

### 🔐 Authentication
```typescript
POST /api/auth/login       // Login
POST /api/auth/register    // Register
POST /api/auth/logout      // Logout
```

### 🛒 Cart
```typescript
GET  /api/cart/list        // Get cart items
POST /api/cart/add         // Add to cart
POST /api/cart/update      // Update quantity
POST /api/cart/remove      // Remove item
```

### ❤️ Wishlist
```typescript
GET  /api/wishlist/list    // Get wishlist
POST /api/wishlist/add     // Add to wishlist
POST /api/wishlist/remove  // Remove from wishlist
```

### 💳 Checkout
```typescript
GET  /api/checkout         // Get checkout session
POST /api/coupon/apply     // Apply coupon
```

### 👤 User
```typescript
GET  /api/user/profile     // Get profile
POST /api/user/profile     // Update profile
GET  /api/user/orders      // Get orders
```

### 🎨 Co-Creation
```typescript
POST /api/co-creation/save // Save project
```

## Migration Pattern

### 1. Remove Old Imports
```typescript
// ❌ Remove these
import { API_BASE_URL } from "@/utils/staticValues";
import Cookies from "js-cookie";
import { apiClient } from "@/utils/apiClient";
```

### 2. Update Fetch Calls
```typescript
// ❌ Before
fetch(`${API_BASE_URL}/endpoint`, {
  headers: { Authorization: `Bearer ${Cookies.get("token")}` }
})

// ✅ After
fetch('/api/endpoint')
```

### 3. Handle Responses
```typescript
const response = await fetch('/api/cart/list');
const data = await response.json();

if (data.success) {
  // Handle success
  setItems(data.data);
} else {
  // Handle error
  toast.error(data.message);
}
```

## Common Patterns

### GET Request
```typescript
async function fetchData() {
  try {
    const response = await fetch('/api/cart/list');
    const data = await response.json();
    
    if (!data.success) {
      throw new Error(data.message);
    }
    
    setData(data.data);
  } catch (error: any) {
    toast.error(error.message);
  }
}
```

### POST Request
```typescript
async function saveData(payload: any) {
  try {
    const response = await fetch('/api/cart/add', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    });
    
    const data = await response.json();
    
    if (!data.success) {
      throw new Error(data.message);
    }
    
    toast.success('Saved successfully!');
  } catch (error: any) {
    toast.error(error.message);
  }
}
```

### DELETE/UPDATE Request
```typescript
async function removeItem(id: string) {
  try {
    const response = await fetch('/api/cart/remove', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ cart_id: id }),
    });
    
    const data = await response.json();
    
    if (!data.success) {
      throw new Error(data.message);
    }
    
    await refreshData();
  } catch (error: any) {
    toast.error(error.message);
  }
}
```

## Creating New API Routes

### Basic Route
```typescript
// app/api/your-endpoint/route.ts
import { createApiRoute, requireAuth } from '@/utils/apiRouteHandler';
import { serverApiClient } from '@/utils/serverApiClient';

export const GET = createApiRoute(
  requireAuth(async (req, { token }) => {
    return await serverApiClient('backend-endpoint');
  })
);
```

### POST with Body
```typescript
export const POST = createApiRoute(
  requireAuth(async (req, { token }) => {
    const body = await req.json();
    
    return await serverApiClient('backend-endpoint', {
      method: 'POST',
      body: JSON.stringify(body),
    });
  })
);
```

### With Query Params
```typescript
export const GET = createApiRoute(
  requireAuth(async (req, { token }) => {
    const { searchParams } = new URL(req.url);
    const id = searchParams.get('id');
    
    return await serverApiClient(`endpoint/${id}`);
  })
);
```

### With FormData
```typescript
import { serverPostFormData } from '@/utils/serverApiClient';

export const POST = createApiRoute(
  requireAuth(async (req, { token }) => {
    const formData = await req.formData();
    
    return await serverPostFormData('upload-endpoint', formData);
  })
);
```

## Debugging

### Check Auth Status
```typescript
// In client component
const user = Cookies.get('getUser');
console.log('User:', user ? JSON.parse(user) : null);
```

### Check API Response
```typescript
const response = await fetch('/api/cart/list');
console.log('Status:', response.status);
console.log('Data:', await response.json());
```

### Network Tab
1. Open Browser DevTools (F12)
2. Go to Network tab
3. Filter by "api/"
4. Check request/response
5. Verify cookies are sent

## Security Checklist

- [✅] No `API_BASE_URL` in client components
- [✅] No `Cookies.get("token")` in client code
- [✅] All auth routes use `/api/auth/*`
- [✅] All data fetching uses `/api/*`
- [✅] Proxy protects sensitive routes
- [✅] Environment variables properly separated
- [✅] HTTP-only cookies for tokens

## Common Issues

### 401 Unauthorized
- Token expired or missing
- Check if user is logged in
- Verify proxy allows the route

### 404 Not Found
- API route doesn't exist
- Check spelling of route path
- Ensure route file is in correct location

### CORS Errors
- Should not happen with Next.js API routes
- If occurs, check if using external domain

### Cookie Not Set
- Check browser DevTools > Application > Cookies
- Verify secure flag matches environment (dev vs prod)
- Check SameSite policy

## Need Help?

1. Check [IMPLEMENTATION_SUMMARY.md](./IMPLEMENTATION_SUMMARY.md)
2. Review [MIGRATION_GUIDE.md](./MIGRATION_GUIDE.md)
3. Look at migrated example: [app/bag/page.tsx](./app/bag/page.tsx)
4. Test API routes in browser Network tab
