Blog>
Snippets

Performance Metrics with Next.js Analytics API

Utilize Next.js 14's integrated analytics API to capture and analyze performance metrics directly from the application.
import { unstable_getServerSession } from 'next-auth';
import { NextRequest, NextResponse } from 'next/server';

export function middleware(req) {
  // Add logic here to send metrics to your analytics endpoint.
  // You can use Next.js' native analytics tool or any third-party service.

  // Example: Sending a page view event to your analytics server.
  // Replace 'YOUR_ANALYTICS_ENDPOINT' with your actual analytics endpoint.
  const endpoint = 'YOUR_ANALYTICS_ENDPOINT';
  fetch(endpoint, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      event: 'pageview',
      path: req.nextUrl.pathname,
    }),
  });

  return NextResponse.next();
}
This code snippet demonstrates how to use a Next.js middleware to capture performance metrics such as page views and send them to an analytics endpoint. Replace 'YOUR_ANALYTICS_ENDPOINT' with the endpoint for your analytics tool. The middleware captures the request's pathname and sends it as a 'pageview' event.
import { reportWebVitals } from 'next/web-vitals';

export function reportHandler(metric) {
  // Logic to log all performance metrics.
  // Here, you can send metrics to your preferred analytics server.
  const { name, value } = metric;

  // You might want to send some metrics conditionally based on their name.
  if (name === 'FCP') { // First Contentful Paint
    // Replace 'YOUR_ANALYTICS_ENDPOINT' with your actual analytics endpoint.
    const endpoint = 'YOUR_ANALYTICS_ENDPOINT';
    fetch(endpoint, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        metricName: name,
        value: value,
      }),
    });
  }
}

// Next.js will automatically call this function when web vitals metrics are recorded
reportWebVitals(reportHandler);
This code snippet demonstrates how to use the reportWebVitals utility from Next.js to hook into the Web Vitals API and log performance metrics. It sends the 'First Contentful Paint' (FCP) metric to the specified analytics endpoint via a POST request. The reportWebVitals function is automatically called by Next.js whenever the Web Vitals metrics are captured.