# Web Vitals Quick Reference

## 🚀 Quick Start (3 Steps)

```tsx
// 1. Import in app/layout.tsx
import { WebVitalsReporter } from './components/WebVitalsReporter';

// 2. Add to layout
export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <WebVitalsReporter />
        {children}
      </body>
    </html>
  );
}

// 3. Set environment variable
NEXT_PUBLIC_SENTRY_DSN=your-sentry-dsn
```

## 📊 Metrics Tracked

| Metric | Name | Good | Poor | What It Measures |
|--------|------|------|------|------------------|
| **LCP** | Largest Contentful Paint | ≤ 2.5s | > 4s | Loading |
| **FID** | First Input Delay | ≤ 100ms | > 300ms | Interactivity |
| **CLS** | Cumulative Layout Shift | ≤ 0.1 | > 0.25 | Stability |
| **TTFB** | Time to First Byte | ≤ 800ms | > 1.8s | Server |
| **FCP** | First Contentful Paint | ≤ 1.8s | > 3s | Rendering |
| **INP** | Interaction to Next Paint | ≤ 200ms | > 500ms | Responsiveness |

## 🎯 API Reference

### reportWebVitals()
Initializes tracking. Call once in root layout.

```tsx
import { reportWebVitals } from '@/lib/monitoring/web-vitals';

useEffect(() => {
  reportWebVitals();
}, []);
```

### getCurrentMetrics()
Gets current metric values programmatically.

```tsx
import { getCurrentMetrics } from '@/lib/monitoring/web-vitals';

const metrics = await getCurrentMetrics();
console.log(metrics);
```

### METRIC_THRESHOLDS
Performance threshold constants.

```tsx
import { METRIC_THRESHOLDS } from '@/lib/monitoring/web-vitals';

if (lcp <= METRIC_THRESHOLDS.LCP.good) {
  console.log('Good LCP!');
}
```

## 🧪 Testing

```bash
# Run tests
npm test -- __tests__/lib/monitoring/web-vitals.test.ts

# Run with coverage
npm test -- --coverage __tests__/lib/monitoring/web-vitals.test.ts

# Watch mode
npm test -- --watch __tests__/lib/monitoring/web-vitals.test.ts
```

## 🐛 Debugging

### View Metrics in Console (Development)

```
[Web Vitals] {
  name: 'LCP',
  value: 1234.56,
  rating: 'good',
  id: 'v3-...'
}
```

### Check Sentry

1. Open Sentry Dashboard
2. Go to **Performance** → **Web Vitals**
3. View metrics and trends

### Create Debug Panel

```tsx
import { getCurrentMetrics } from '@/lib/monitoring/web-vitals';

export function DebugPanel() {
  const [metrics, setMetrics] = useState([]);

  useEffect(() => {
    getCurrentMetrics().then(setMetrics);
  }, []);

  return (
    <div>
      {metrics.map(m => (
        <div key={m.name}>{m.name}: {m.value}</div>
      ))}
    </div>
  );
}
```

## 🎨 Where Metrics Are Sent

1. **Sentry Performance Monitoring**
   - Measurements (raw values)
   - Breadcrumbs (context)
   - Warnings (if poor)

2. **Google Analytics 4** (if available)
   - Custom events
   - Event category: "Web Vitals"

3. **Browser Console** (development only)
   - Debug logs with values and ratings

## 🚨 Common Issues

### No Metrics in Sentry
```bash
# Check Sentry DSN is set
echo $NEXT_PUBLIC_SENTRY_DSN

# Verify Sentry is initialized
cat sentry.client.config.ts
```

### Tests Failing
```bash
# Install dependencies
npm install

# Clear cache
npx jest --clearCache

# Run again
npm test
```

### SSR Errors
- Always use `<WebVitalsReporter />` (client component)
- Or wrap in `useEffect` hook
- Never call directly in server components

## 📈 Performance Tips

### Improve LCP (> 4s)
- Use Next.js `<Image>` with `priority`
- Implement CDN
- Optimize images (WebP, AVIF)
- Preload critical resources

### Improve FID (> 300ms)
- Code split with `dynamic()`
- Use Web Workers
- Optimize React renders
- Defer non-critical JS

### Improve CLS (> 0.25)
- Set image dimensions
- Reserve space for ads
- Use `font-display: swap`
- Avoid layout shifts

## 📚 Full Documentation

- **API Docs**: `lib/monitoring/README.md`
- **Integration**: `lib/monitoring/INTEGRATION.md`
- **Summary**: `lib/monitoring/IMPLEMENTATION_SUMMARY.md`
- **Checklist**: `lib/monitoring/CHECKLIST.md`

## 🔗 External Resources

- [Web Vitals](https://web.dev/vitals/)
- [Sentry Performance](https://docs.sentry.io/product/performance/)
- [Google Analytics](https://developers.google.com/analytics)
- [Next.js Performance](https://nextjs.org/docs/app/building-your-application/optimizing)

---

**Version**: 1.0.0
**Last Updated**: 2026-01-03
**Package**: `web-vitals@5.1.0`
