performance2025-04-08·8 min·126/348

Vercel Speed Insights 설정

Vercel Speed Insights를 설정하여 웹 애플리케이션의 성능을 모니터링하고 최적화하는 방법을 알아봅니다.

Vercel Speed Insights 설정

Introduction

Vercel Speed Insights는 웹 애플리케이션의 성능 메트릭을 수집하고 분석하는 도구입니다. Core Web Vitals를 포함한 다양한 성능 지표를 모니터링하여 사용자 경험을 개선할 수 있습니다. 이 글에서는 Vercel Speed Insights를 설정하고 활용하는 방법을 알아보겠습니다.

Environment

  • Vercel 프로젝트 (Next.js 14+)
  • Vercel Analytics 플랜
  • React 18+
  • TypeScript

Problem

웹 애플리케이션의 성능을 측정하고 최적화하기 위한 데이터가 부족합니다:

// 기본 성능 측정 코드
const startTime = performance.now();

// 페이지 렌더링 후
const endTime = performance.now();
console.log(`Render time: ${endTime - startTime}ms`);

// 이 방법은 정확하지 않고, 실제 사용자 경험을 반영하지 못함

Analysis

Vercel Speed Insights가 수집하는 메트릭:

  1. LCP (Largest Contentful Paint): 가장 큰 콘텐츠가 렌더링되는 시간
  2. FID (First Input Delay): 첫 번째 사용자 입력까지의 지연 시간
  3. CLS (Cumulative Layout Shift): 레이아웃 시프트 누적 값
  4. TTFB (Time to First Byte): 첫 번째 바이트까지의 시간
  5. INP (Interaction to Next Paint): 상호작용 후 다음 페인트까지의 시간

Solution

1. Speed Insights 설치

npm install @vercel/speed-insights

2. Next.js 앱에 추가

// app/layout.js
import { SpeedInsights } from "@vercel/speed-insights";

export default function RootLayout({ children }) {
  return (
    
      
        {children}
        
      
    
  );
}

3. 커스텀 메트릭 추가

// lib/custom-metrics.js
import { reportWebVitals } from '@vercel/speed-insights';

export function initCustomMetrics() {
  // 커스텀 성능 메트릭 수집
  if (typeof window !== 'undefined') {
    // 페이지 로드 시간
    window.addEventListener('load', () => {
      const loadTime = performance.now();
      reportWebVitals({
        metric: 'page-load-time',
        value: loadTime,
        rating: loadTime < 3000 ? 'good' : loadTime < 5000 ? 'needs-improvement' : 'poor'
      });
    });
    
    // 리소스 로드 시간
    const observer = new PerformanceObserver((list) => {
      list.getEntries().forEach((entry) => {
        reportWebVitals({
          metric: 'resource-load-time',
          value: entry.duration,
          name: entry.name
        });
      });
    });
    
    observer.observe({ entryTypes: ['resource'] });
  }
}

4. 커스텀 수집기 설정

// app/layout.js
import { SpeedInsights } from "@vercel/speed-insights";

export default function RootLayout({ children }) {
  return (
    
      
        {children}
        
      
    
  );
}
// app/api/speed-insights/route.js
import { NextResponse } from 'next/server';

export async function POST(request) {
  const data = await request.json();
  
  // 커스텀 처리 로직
  console.log('Speed Insights:', data);
  
  // 데이터베이스에 저장
  // await saveMetrics(data);
  
  return NextResponse.json({ success: true });
}

5. 성능 대시보드 구현

// components/PerformanceDashboard.jsx
'use client';

import { useEffect, useState } from 'react';

export default function PerformanceDashboard() {
  const [metrics, setMetrics] = useState(null);
  const [loading, setLoading] = useState(true);
  
  useEffect(() => {
    async function fetchMetrics() {
      try {
        const response = await fetch('/api/metrics');
        const data = await response.json();
        setMetrics(data);
      } catch (error) {
        console.error('Failed to fetch metrics:', error);
      } finally {
        setLoading(false);
      }
    }
    
    fetchMetrics();
  }, []);
  
  if (loading) return 
Loading...
; if (!metrics) return
No metrics available
; return (

Performance Metrics

LCP

{metrics.lcp.toFixed(2)}s

FID

{metrics.fid.toFixed(2)}ms

CLS

{metrics.cls.toFixed(3)}

); } function getRatingClass(value) { if (value < 0.5) return 'good'; if (value < 1) return 'needs-improvement'; return 'poor'; }

6. 성능 알림 설정

// lib/performance-alerts.js
export function checkPerformanceThresholds(metrics) {
  const alerts = [];
  
  if (metrics.lcp > 2.5) {
    alerts.push({
      type: 'warning',
      metric: 'LCP',
      value: metrics.lcp,
      threshold: 2.5,
      message: `LCP is ${metrics.lcp.toFixed(2)}s (threshold: 2.5s)`
    });
  }
  
  if (metrics.fid > 100) {
    alerts.push({
      type: 'warning',
      metric: 'FID',
      value: metrics.fid,
      threshold: 100,
      message: `FID is ${metrics.fid.toFixed(2)}ms (threshold: 100ms)`
    });
  }
  
  if (metrics.cls > 0.1) {
    alerts.push({
      type: 'error',
      metric: 'CLS',
      value: metrics.cls,
      threshold: 0.1,
      message: `CLS is ${metrics.cls.toFixed(3)} (threshold: 0.1)`
    });
  }
  
  return alerts;
}

Lessons Learned

  1. 지속적 모니터링: Speed Insights를 설정하면 지속적으로 성능을 모니터링할 수 있습니다.
  2. 커스텀 메트릭: 프로젝트에 맞는 커스텀 메트릭을 추가하면 더 정확한 분석이 가능합니다.
  3. 알림 설정: 성능 임계값을 초과하면 알림을 받을 수 있도록 설정해야 합니다.
  4. 데이터 분석: 수집된 데이터를 분석하여 성능 최적화 기회를 발견해야 합니다.
  5. 사용자 경험: 기술적인 메트릭보다 사용자 경험에 초점을 맞춰야 합니다.

This blog does not accept any external sponsorships, affiliate marketing, or ad revenue.