All files / src/app/api/admin/monitoring/web-vitals route.ts

0% Statements 0/174
100% Branches 0/0
0% Functions 0/1
0% Lines 0/174

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175                                                                                                                                                                                                                                                                                                                                                             
export const dynamic = 'force-dynamic';

import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { addSecurityHeaders } from '@/lib/security';
import {
  withAdmin,
  withErrorHandling,
  type ApiSuccessResponse,
  type ApiErrorResponse,
} from '@/lib/api';
import {
  calculateWebVitalStats,
  normalizePagePath,
  getWorstMetric,
  type WebVitalName,
  type WebVitalStats,
  type PageWebVitals,
} from '@/lib/observability/web-vitals';

/**
 * Web Vitals API Response
 */
interface WebVitalsResponse {
  /** Time period for the data */
  period: {
    hours: number;
    from: string;
    to: string;
  };
  /** Overall Web Vitals statistics */
  vitals: Record<WebVitalName, WebVitalStats>;
  /** Web Vitals broken down by page */
  byPage: PageWebVitals[];
  /** Total number of measurements */
  totalMeasurements: number;
}

/**
 * GET /api/admin/monitoring/web-vitals
 *
 * Returns aggregated Web Vitals metrics from RUM data.
 * Supports filtering by time period (hours query param).
 *
 * @param hours - Number of hours to look back (default: 24, max: 168)
 */
async function handleGet(
  request: Request
): Promise<NextResponse<ApiSuccessResponse<WebVitalsResponse> | ApiErrorResponse>> {
  const url = new URL(request.url);
  const hoursParam = url.searchParams.get('hours');
  const hours = Math.min(Math.max(parseInt(hoursParam || '24', 10) || 24, 1), 168);

  const now = new Date();
  const since = new Date(now.getTime() - hours * 60 * 60 * 1000);

  // Fetch all vitals events from the time period
  const vitalsEvents = await prisma.rumEvent.findMany({
    where: {
      type: 'vitals',
      timestamp: { gte: since },
    },
    select: {
      url: true,
      data: true,
      timestamp: true,
    },
    orderBy: { timestamp: 'desc' },
  });

  // Extract values for each metric
  const metricValues: Record<WebVitalName, number[]> = {
    LCP: [],
    CLS: [],
    FID: [],
    INP: [],
    FCP: [],
    TTFB: [],
  };

  // Also track by page
  const pageMetrics: Map<string, Record<WebVitalName, number[]>> = new Map();

  for (const event of vitalsEvents) {
    const data = event.data as Record<string, unknown>;
    const normalizedPath = normalizePagePath(event.url);

    // Initialize page metrics if needed
    if (!pageMetrics.has(normalizedPath)) {
      pageMetrics.set(normalizedPath, {
        LCP: [],
        CLS: [],
        FID: [],
        INP: [],
        FCP: [],
        TTFB: [],
      });
    }
    const pageData = pageMetrics.get(normalizedPath)!;

    // Extract each metric
    const metrics: WebVitalName[] = ['LCP', 'CLS', 'FID', 'INP', 'FCP', 'TTFB'];
    for (const metric of metrics) {
      const value = data[metric];
      if (typeof value === 'number' && !isNaN(value) && value >= 0) {
        metricValues[metric].push(value);
        pageData[metric].push(value);
      }
    }
  }

  // Calculate overall stats for each metric
  const vitals: Record<WebVitalName, WebVitalStats> = {
    LCP: calculateWebVitalStats('LCP', metricValues.LCP),
    CLS: calculateWebVitalStats('CLS', metricValues.CLS),
    FID: calculateWebVitalStats('FID', metricValues.FID),
    INP: calculateWebVitalStats('INP', metricValues.INP),
    FCP: calculateWebVitalStats('FCP', metricValues.FCP),
    TTFB: calculateWebVitalStats('TTFB', metricValues.TTFB),
  };

  // Calculate stats by page
  const byPage: PageWebVitals[] = [];
  for (const [url, metrics] of pageMetrics.entries()) {
    const pageStats: Partial<Record<WebVitalName, WebVitalStats>> = {};
    let hasData = false;

    for (const metric of ['LCP', 'CLS', 'FID', 'INP', 'FCP', 'TTFB'] as WebVitalName[]) {
      if (metrics[metric].length > 0) {
        pageStats[metric] = calculateWebVitalStats(metric, metrics[metric]);
        hasData = true;
      }
    }

    if (hasData) {
      byPage.push({
        url,
        metrics: pageStats,
        worstMetric: getWorstMetric(pageStats),
      });
    }
  }

  // Sort pages by worst performing first
  byPage.sort((a, b) => {
    const aRating = a.worstMetric?.rating || 'good';
    const bRating = b.worstMetric?.rating || 'good';
    const ratingOrder = { poor: 0, 'needs-improvement': 1, good: 2 };
    return ratingOrder[aRating] - ratingOrder[bRating];
  });

  // Limit to top 20 pages
  const topPages = byPage.slice(0, 20);

  const response: WebVitalsResponse = {
    period: {
      hours,
      from: since.toISOString(),
      to: now.toISOString(),
    },
    vitals,
    byPage: topPages,
    totalMeasurements: vitalsEvents.length,
  };

  return addSecurityHeaders(
    NextResponse.json({
      success: true,
      data: response,
    })
  ) as NextResponse<ApiSuccessResponse<WebVitalsResponse> | ApiErrorResponse>;
}

export const GET = withErrorHandling(withAdmin(handleGet));