Next.js Monitoring and Analytics

Overview

Monitoring and analytics help you understand application performance, user behavior, and potential issues.

Vercel Analytics

Installation

npm install @vercel/analytics

Usage

// app/layout.tsx
import { Analytics } from '@vercel/analytics/react'

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        {children}
        <Analytics />
      </body>
    </html>
  )
}

Web Vitals

Monitoring Core Metrics

// app/web-vitals.tsx
'use client'

import { useReportWebVitals } from 'next/web-vitals'

export function WebVitals() {
  useReportWebVitals((metric) => {
    console.log(metric)
    
    // 发送到分析服务
    fetch('/api/analytics', {
      method: 'POST',
      body: JSON.stringify(metric),
    })
  })
}

Metric Descriptions

  • CLS: Cumulative Layout Shift
  • FID: First Input Delay
  • FCP: First Contentful Paint
  • LCP: Largest Contentful Paint
  • TTFB: Time to First Byte

Error Monitoring

Sentry Integration

npm install @sentry/nextjs
// sentry.client.config.js
import * as Sentry from '@sentry/nextjs'

Sentry.init({
  dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
  tracesSampleRate: 1.0,
})

// sentry.server.config.js
import * as Sentry from '@sentry/nextjs'

Sentry.init({
  dsn: process.env.SENTRY_DSN,
  tracesSampleRate: 1.0,
})

Custom Logging

Logging Service

// lib/logger.ts
export function log(level: 'info' | 'warn' | 'error', message: string, data?: any) {
  const logData = {
    level,
    message,
    data,
    timestamp: new Date().toISOString(),
  }
  
  if (process.env.NODE_ENV === 'production') {
    // 发送到日志服务
    fetch('/api/logs', {
      method: 'POST',
      body: JSON.stringify(logData),
    })
  } else {
    console[level](message, data)
  }
}

Performance Monitoring

Custom Metrics

'use client'

import { useEffect } from 'react'

export function PerformanceMonitor() {
  useEffect(() => {
    // 监控 API 请求时间
    const observer = new PerformanceObserver((list) => {
      for (const entry of list.getEntries()) {
        if (entry.entryType === 'resource') {
          console.log(`${entry.name}: ${entry.duration}ms`)
        }
      }
    })
    
    observer.observe({ entryTypes: ['resource'] })
    
    return () => observer.disconnect()
  }, [])
  
  return null
}

Best Practices

1. Set Up Alerts

// lib/alert.ts
export function sendAlert(message: string, severity: 'low' | 'high') {
  if (severity === 'high') {
    // 发送紧急通知
    fetch('/api/alerts', {
      method: 'POST',
      body: JSON.stringify({ message, severity }),
    })
  }
}

2. Regular Reviews

  • Review performance metrics weekly
  • Monitor error rate trends
  • Analyze user behavior

3. Optimize Response

  • Set performance budgets
  • Automate performance testing
  • Continuously optimize

Previous Chapter: Next.js Environment Variables | Next Chapter: Next.js Configuration