|
| 1 | +"use client"; |
| 2 | + |
| 3 | +import { useReportWebVitals } from "next/web-vitals"; |
| 4 | + |
| 5 | +import * as Sentry from "@sentry/nextjs"; |
| 6 | + |
| 7 | +/** |
| 8 | + * Next.js Web Vitals를 Sentry로 전송하는 컴포넌트 |
| 9 | + * |
| 10 | + * 측정되는 메트릭: |
| 11 | + * - CLS (Cumulative Layout Shift): 레이아웃 안정성 |
| 12 | + * - FCP (First Contentful Paint): 첫 콘텐츠 표시 시간 |
| 13 | + * - FID (First Input Delay): 첫 입력 지연 (INP로 대체 예정) |
| 14 | + * - INP (Interaction to Next Paint): 상호작용 응답성 |
| 15 | + * - LCP (Largest Contentful Paint): 최대 콘텐츠 표시 시간 |
| 16 | + * - TTFB (Time to First Byte): 첫 바이트까지의 시간 |
| 17 | + */ |
| 18 | +export function WebVitals() { |
| 19 | + useReportWebVitals((metric) => { |
| 20 | + // Web Vitals를 Sentry 트랜잭션으로 전송 |
| 21 | + const { name, value, rating, navigationType, id } = metric; |
| 22 | + |
| 23 | + // Sentry의 현재 트랜잭션에 measurement 추가 (v7 API) |
| 24 | + const transaction = Sentry.getCurrentHub().getScope()?.getTransaction(); |
| 25 | + if (transaction) { |
| 26 | + // CLS는 unitless 메트릭이므로 unit을 생략, 나머지는 millisecond |
| 27 | + if (name === "CLS") { |
| 28 | + transaction.setMeasurement(name, value); |
| 29 | + } else { |
| 30 | + transaction.setMeasurement(name, value, "millisecond"); |
| 31 | + } |
| 32 | + transaction.setTag(`${name}.rating`, rating); |
| 33 | + transaction.setTag("navigation.type", navigationType); |
| 34 | + } |
| 35 | + |
| 36 | + // 각 메트릭을 개별 컨텍스트 키로 저장 (덮어쓰기 방지) |
| 37 | + Sentry.getCurrentScope().setContext(`web-vitals.${name}`, { |
| 38 | + value, |
| 39 | + rating, |
| 40 | + navigationType, |
| 41 | + id, |
| 42 | + }); |
| 43 | + |
| 44 | + // 개발 환경에서는 콘솔에도 출력 |
| 45 | + if (process.env.NODE_ENV === "development") { |
| 46 | + console.log(`[Web Vitals] ${name}:`, { |
| 47 | + value: name === "CLS" ? value.toFixed(3) : `${Math.round(value)}ms`, |
| 48 | + rating, |
| 49 | + navigationType, |
| 50 | + }); |
| 51 | + } |
| 52 | + }); |
| 53 | + |
| 54 | + return null; |
| 55 | +} |
0 commit comments