Next.js course ยท Module 8: Deployment and Production

Performance monitoring and error analytics

21 min read ยท
In this lesson12

In production Next.js applications, performance monitoring and error tracking are key to maintaining high quality of delivered services. In this module, we will learn about tools and techniques that will allow us to effectively monitor the application, detect problems before users do, and optimize performance on an ongoing basis.

The importance of monitoring in production applications

Monitoring is the process of continuously observing an application in order to:

  1. Early detection of problems - before they affect users
  2. Performance tracking - loading times, Core Web Vitals, throughput
  3. Analysis of user behavior - how users use the application
  4. Identifying bottlenecks - places requiring optimization
  5. Ensuring SLA - meeting agreed service levels

Types of monitoring

1. Performance Monitoring

  • Core Web Vitals (LCP, INP, CLS)
  • Page loading times
  • API response times
  • Resource consumption (CPU, memory)

2. Error Monitoring

  • JavaScript errors
  • API errors
  • Network errors
  • Stack traces

3. Infrastructure monitoring

  • Server availability
  • Resource consumption
  • Network metrics

4. User Experience Monitoring (UX)

  • Real User Monitoring (RUM)
  • Session recordings
  • Heat maps
  • User flows

Integration with Sentry for error monitoring

Sentry is one of the most popular tools for error monitoring in JavaScript and Next.js applications.

1. Installation and configuration of Sentry

npm install @sentry/nextjs
# or
yarn add @sentry/nextjs

Create the configuration files:

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

Sentry.init({
  dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,

  // Environment settings
  environment: process.env.NODE_ENV,

  // Sample rate for performance transactions
  tracesSampleRate: 1.0,

  // Enable Replay for user sessions
  replaysSessionSampleRate: 0.1, // 10% of sessions
  replaysOnErrorSampleRate: 1.0,  // 100% of sessions with errors

  // Integrations
  integrations: [
    new Sentry.Replay({
      maskAllText: false,
      blockAllMedia: false,
    }),
  ],

  // Filtering errors
  beforeSend(event) {
    // Ignore certain types of errors
    if (event.exception) {
      const error = event.exception.values[0];
      if (error.type === 'ChunkLoadError') {
        return null; // Ignore chunk loading errors
      }
    }
    return event;
  },
});
// sentry.server.config.js
import * as Sentry from '@sentry/nextjs';

Sentry.init({
  dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
  environment: process.env.NODE_ENV,
  tracesSampleRate: 1.0,

  // Additional options for the server
  debug: false,

  // Integrations specific to Node.js
  integrations: [
    new Sentry.Integrations.Http({ tracing: true }),
  ],
});
// sentry.edge.config.js
import * as Sentry from '@sentry/nextjs';

Sentry.init({
  dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
  environment: process.env.NODE_ENV,
  tracesSampleRate: 1.0,
  debug: false,
});

2. Configuring Next.js for Sentry

// next.config.js
const { withSentryConfig } = require('@sentry/nextjs');

const nextConfig = {
  // Your standard Next.js configuration
};

const sentryWebpackPluginOptions = {
  // Additional configuration options for the Sentry webpack plugin
  silent: true, // Silence Sentry logs during the build
  org: process.env.SENTRY_ORG,
  project: process.env.SENTRY_PROJECT,
};

module.exports = withSentryConfig(nextConfig, sentryWebpackPluginOptions);

3. Adding context to errors

// lib/sentry.ts
import * as Sentry from '@sentry/nextjs';

// Function to add user context
export function setUserContext(user: { id: string; email: string; name?: string }) {
  Sentry.setUser({
    id: user.id,
    email: user.email,
    username: user.name,
  });
}

// Function to add tags
export function addTags(tags: Record<string, string>) {
  Sentry.setTags(tags);
}

// Function for manual error reporting
export function captureException(error: Error, context?: Record<string, any>) {
  Sentry.withScope((scope) => {
    if (context) {
      scope.setContext('additional_info', context);
    }
    Sentry.captureException(error);
  });
}

// Function for performance tracking
export function startTransaction(name: string, op: string) {
  return Sentry.startTransaction({ name, op });
}

4. Using Sentry in components

// components/ErrorBoundary.tsx
'use client';

import React from 'react';
import * as Sentry from '@sentry/nextjs';

interface ErrorBoundaryState {
  hasError: boolean;
  eventId?: string;
}

class ErrorBoundary extends React.Component<
  React.PropsWithChildren<{}>,
  ErrorBoundaryState
> {
  constructor(props: React.PropsWithChildren<{}>) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(_: Error): ErrorBoundaryState {
    return { hasError: true };
  }

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    const eventId = Sentry.captureException(error, {
      contexts: {
        react: {
          componentStack: errorInfo.componentStack,
        },
      },
    });

    this.setState({ eventId });
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="error-fallback">
          <h2>Oops! Something went wrong</h2>
          <p>An unexpected error occurred. Our team has been notified.</p>
          <details style={{ whiteSpace: 'pre-wrap' }}>
            Error ID: {this.state.eventId}
          </details>
          <button onClick={() => window.location.reload()}>
            Refresh the page
          </button>
        </div>
      );
    }

    return this.props.children;
  }
}

export default ErrorBoundary;

Monitoring Core Web Vitals

Core Web Vitals are key performance metrics that Google uses to evaluate the user experience:

  • LCP (Largest Contentful Paint) - loading time of the largest element
  • INP (Interaction to Next Paint) - how quickly the page responds to user interactions (replaced FID in 2024)
  • CLS (Cumulative Layout Shift) - layout instability

1. Web Vitals implementation in Next.js

// lib/web-vitals.ts
import { onCLS, onINP, onFCP, onLCP, onTTFB } from 'web-vitals';
import * as Sentry from '@sentry/nextjs';

interface WebVitalMetric {
  name: string;
  value: number;
  id: string;
  delta: number;
}

// Function for reporting metrics
function sendToAnalytics(metric: WebVitalMetric) {
  // Send to Google Analytics
  if (typeof window !== 'undefined' && window.gtag) {
    window.gtag('event', metric.name, {
      event_category: 'Web Vitals',
      event_label: metric.id,
      value: Math.round(metric.name === 'CLS' ? metric.value * 1000 : metric.value),
      non_interaction: true,
    });
  }

  // Send to Sentry
  Sentry.addBreadcrumb({
    category: 'web-vital',
    message: `${metric.name}: ${metric.value}`,
    level: 'info',
    data: {
      name: metric.name,
      value: metric.value,
      id: metric.id,
      delta: metric.delta,
    },
  });

  // In case of poor results, send as event to Sentry
  const thresholds = {
    LCP: 2500,
    INP: 200,
    CLS: 0.1,
  };

  if (metric.value > thresholds[metric.name as keyof typeof thresholds]) {
    Sentry.captureMessage(`Poor ${metric.name}: ${metric.value}`, 'warning');
  }
}

// Initialize Web Vitals measurements
export function initWebVitals() {
  onCLS(sendToAnalytics);
  onINP(sendToAnalytics);
  onFCP(sendToAnalytics);
  onLCP(sendToAnalytics);
  onTTFB(sendToAnalytics);
}

2. Component for monitoring Web Vitals

// components/WebVitalsReporter.tsx
'use client';

import { useEffect } from 'react';
import { useReportWebVitals } from 'next/web-vitals';

export default function WebVitalsReporter() {
  useReportWebVitals((metric) => {
    // Send to various analytics systems
    switch (metric.name) {
      case 'FCP':
      case 'LCP':
      case 'CLS':
      case 'INP':
      case 'TTFB':
        // Send to your own API
        fetch('/api/analytics/web-vitals', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(metric),
        }).catch(console.error);
        break;
      default:
        break;
    }
  });

  return null;
}

3. API endpoint for collecting metrics

// app/api/analytics/web-vitals/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma'; // Let's assume you use Prisma

export async function POST(request: NextRequest) {
  try {
    const metric = await request.json();

    // Basic validation
    if (!metric.name || !metric.value) {
      return NextResponse.json({ error: 'Invalid metric data' }, { status: 400 });
    }

    // Save to the database
    await prisma.webVitalMetric.create({
      data: {
        name: metric.name,
        value: metric.value,
        id: metric.id,
        delta: metric.delta,
        url: request.headers.get('referer') || '',
        userAgent: request.headers.get('user-agent') || '',
        timestamp: new Date(),
      },
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Error saving web vital metric:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}

Performance monitoring with New Relic

New Relic offers a comprehensive solution for performance monitoring of Next.js applications.

1. Configuring New Relic

npm install newrelic
// newrelic.js (in the project root)
'use strict';

exports.config = {
  app_name: ['Next.js App'],
  license_key: process.env.NEW_RELIC_LICENSE_KEY,

  // Logging configuration
  logging: {
    level: 'info',
  },

  // Enable distributed tracing
  distributed_tracing: {
    enabled: true,
  },

  // Browser monitoring
  browser_monitoring: {
    enable: true,
  },

  // Configuration specific to Next.js
  allow_all_headers: true,
  attributes: {
    exclude: [
      'request.headers.cookie',
      'request.headers.authorization',
      'request.headers.x-*',
    ],
  },
};
// next.config.js
if (process.env.NODE_ENV === 'production') {
  require('./newrelic');
}

const nextConfig = {
  // Your Next.js configuration
};

module.exports = nextConfig;

2. Custom instrumentation in New Relic

// lib/monitoring.ts
import newrelic from 'newrelic';

// Function to track custom metrics
export function recordCustomMetric(name: string, value: number) {
  if (process.env.NODE_ENV === 'production') {
    newrelic.recordMetric(name, value);
  }
}

// Function to track business events
export function recordCustomEvent(eventType: string, attributes: Record<string, any>) {
  if (process.env.NODE_ENV === 'production') {
    newrelic.recordCustomEvent(eventType, attributes);
  }
}

// Wrapper for API calls with automatic tracking
export async function instrumentedApiCall<T>(
  name: string,
  apiCall: () => Promise<T>
): Promise<T> {
  const startTime = Date.now();

  try {
    const result = await apiCall();

    // Save success metrics
    recordCustomMetric(`Custom/API/${name}/Duration`, Date.now() - startTime);
    recordCustomEvent('APICall', {
      name,
      status: 'success',
      duration: Date.now() - startTime,
    });

    return result;
  } catch (error) {
    // Save error metrics
    recordCustomMetric(`Custom/API/${name}/Error`, 1);
    recordCustomEvent('APICall', {
      name,
      status: 'error',
      duration: Date.now() - startTime,
      error: error.message,
    });

    throw error;
  }
}

Vercel Analytics - Next-generation monitoring in Quantum Metropolis

In Quantum Metropolis 2150, every user interaction is monitored by advanced analytics systems. Vercel Analytics is a native monitoring solution for Next.js applications, designed with user privacy and GDPR compliance in mind. Unlike Google Analytics, Vercel Analytics runs directly in the Vercel Edge Network, which ensures minimal latency and accurate measurements.

Vercel Analytics vs Google Analytics

Before you decide on an analytics tool, it's worth understanding the key differences:

Vercel Analytics:

  • Integrated with Vercel Edge Network
  • Automatic tracking of Core Web Vitals
  • Privacy-first (no cookies, GDPR-compliant)
  • Zero configuration for basic metrics
  • Real-time data in the Vercel dashboard
  • Paid plan for a larger number of page views
  • Basic segmentation features

Google Analytics 4:

  • Advanced user segmentation
  • Funnel analysis and conversion tracking
  • Integration with Google Ads and other Google tools
  • Free plan for most use cases
  • Requires cookie consent (GDPR compliance)
  • Greater impact on page performance
  • More complicated configuration

Real User Monitoring (RUM) with Vercel Analytics

Real User Monitoring is a technique for collecting data about real user experiences, not synthetic tests. Vercel Analytics automatically tracks all key performance metrics.

Installing Vercel Analytics

npm install @vercel/analytics
# or
yarn add @vercel/analytics
# or
pnpm add @vercel/analytics

Basic configuration

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

export default function RootLayout({
  children
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="pl">
      <body>
        {children}
        <Analytics />
      </body>
    </html>
  );
}

That's all! Vercel Analytics will automatically start tracking:

  • Page views
  • Unique visitors
  • Top pages
  • Top referrers
  • Devices and browsers
  • Geographic data

Core Web Vitals Tracking

Core Web Vitals are key web performance metrics that Google uses as ranking signals. Vercel Analytics automatically tracks all three metrics:

1. Largest Contentful Paint (LCP)

  • Measures the loading time of the largest content element
  • Target: < 2.5s
  • Affects: First impression, perceived performance

2. Interaction to Next Paint (INP)

  • Measures responsiveness to user interactions
  • INP target: < 200ms (INP replaced FID in 2024)
  • Affects: Interactivity, user experience

3. Cumulative Layout Shift (CLS)

  • Measures visual stability (unexpected layout shifts)
  • Target: < 0.1
  • Affects: Visual stability, user frustration

Access to Core Web Vitals in code

You can programmatically access Web Vitals metrics:

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

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

export function WebVitals() {
  useReportWebVitals((metric) => {
    console.log(metric);

    // You can send metrics to your own endpoint
    if (metric.label === 'web-vital') {
      fetch('/api/analytics/web-vitals', {
        method: 'POST',
        body: JSON.stringify(metric),
        headers: {
          'Content-Type': 'application/json'
        }
      });
    }
  });

  return null;
}
// app/layout.tsx
import { Analytics } from '@vercel/analytics/react';
import { WebVitals } from './web-vitals';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="pl">
      <body>
        {children}
        <Analytics />
        <WebVitals />
      </body>
    </html>
  );
}

Custom Events - tracking custom interactions

Vercel Analytics allows tracking custom events for specific user actions:

'use client';

import { track } from '@vercel/analytics';

export default function NewsletterForm() {
  const handleSubscribe = async (email: string) => {
    try {
      await subscribeToNewsletter(email);

      // Track successful subscription
      track('Newsletter Subscribe', {
        email_domain: email.split('@')[1],
        source: 'homepage'
      });

    } catch (error) {
      // Track error
      track('Newsletter Subscribe Error', {
        error: error.message
      });
    }
  };

  return (
    <form onSubmit={(e) => {
      e.preventDefault();
      const email = e.target.email.value;
      handleSubscribe(email);
    }}>
      <input type="email" name="email" required />
      <button type="submit">Subscribe</button>
    </form>
  );
}

Advanced custom events

'use client';

import { track } from '@vercel/analytics';

export default function ProductPage({ product }: { product: Product }) {
  // Track product view
  useEffect(() => {
    track('Product View', {
      product_id: product.id,
      product_name: product.name,
      product_category: product.category,
      product_price: product.price
    });
  }, [product]);

  // Track add to cart
  const handleAddToCart = () => {
    track('Add to Cart', {
      product_id: product.id,
      quantity: 1,
      value: product.price
    });

    addToCart(product);
  };

  // Track checkout start
  const handleCheckout = () => {
    track('Begin Checkout', {
      value: cartTotal,
      items: cartItems.length
    });

    router.push('/checkout');
  };

  return (
    <div>
      <h1>{product.name}</h1>
      <p>{product.price} PLN</p>
      <button onClick={handleAddToCart}>Add to cart</button>
      <button onClick={handleCheckout}>Buy now</button>
    </div>
  );
}

Vercel Speed Insights - real-time performance monitoring

Speed Insights is an Analytics extension that provides detailed information about application performance for real users.

Installation

npm install @vercel/speed-insights

Configuration

// app/layout.tsx
import { Analytics } from '@vercel/analytics/react';
import { SpeedInsights } from '@vercel/speed-insights/next';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="pl">
      <body>
        {children}
        <Analytics />
        <SpeedInsights />
      </body>
    </html>
  );
}

What does Speed Insights track?

  1. Performance Score

    • Overall performance rating (0-100)
    • Based on Core Web Vitals and other metrics
  2. Field Data (RUM)

    • Real data from users
    • Segmented by device type, connection speed, geographic location
  3. Lab Data

    • Synthetic performance tests
    • Controlled conditions for consistency
  4. Opportunities

    • Specific optimization suggestions
    • Estimated time savings

Combination with other analytics tools

You can combine Vercel Analytics with other tools for a fuller picture:

// app/layout.tsx
import { Analytics } from '@vercel/analytics/react';
import { SpeedInsights } from '@vercel/speed-insights/next';
import { GoogleAnalytics } from '@next/third-parties/google';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="pl">
      <body>
        {children}

        {/* Vercel Analytics - for Core Web Vitals and basic metrics */}
        <Analytics />
        <SpeedInsights />

        {/* Google Analytics - for advanced segmentation */}
        <GoogleAnalytics gaId={process.env.NEXT_PUBLIC_GA_ID} />
      </body>
    </html>
  );
}

Best practices for Vercel Analytics

1. Use environment-specific tracking

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

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="pl">
      <body>
        {children}

        {/* Only in production */}
        {process.env.NODE_ENV === 'production' && <Analytics />}
      </body>
    </html>
  );
}

2. Group custom events logically

// lib/analytics.ts
import { track } from '@vercel/analytics';

export const analytics = {
  // User events
  user: {
    signup: (method: string) => track('User Signup', { method }),
    login: (method: string) => track('User Login', { method }),
    logout: () => track('User Logout')
  },

  // E-commerce events
  ecommerce: {
    viewProduct: (productId: string) =>
      track('Product View', { product_id: productId }),
    addToCart: (productId: string, value: number) =>
      track('Add to Cart', { product_id: productId, value }),
    purchase: (orderId: string, value: number) =>
      track('Purchase', { order_id: orderId, value })
  },

  // Engagement events
  engagement: {
    shareContent: (contentType: string, method: string) =>
      track('Share', { content_type: contentType, method }),
    search: (query: string) =>
      track('Search', { search_term: query }),
    playVideo: (videoId: string) =>
      track('Video Play', { video_id: videoId })
  }
};

3. Monitor the conversion funnel

'use client';

import { track } from '@vercel/analytics';

export default function CheckoutFlow() {
  // Step 1: View cart
  useEffect(() => {
    track('Checkout Step 1 - Cart', {
      items: cart.length,
      value: cartTotal
    });
  }, []);

  // Step 2: Shipping info
  const handleShippingSubmit = () => {
    track('Checkout Step 2 - Shipping', {
      value: cartTotal
    });
  };

  // Step 3: Payment
  const handlePaymentSubmit = () => {
    track('Checkout Step 3 - Payment', {
      value: cartTotal,
      payment_method: selectedPaymentMethod
    });
  };

  // Step 4: Confirmation
  const handleOrderComplete = (orderId: string) => {
    track('Purchase Complete', {
      order_id: orderId,
      value: cartTotal,
      items: cart.length
    });
  };

  return <CheckoutSteps />;
}

Dashboard and reports

The Vercel Analytics Dashboard offers:

  1. Overview

    • Total page views
    • Unique visitors
    • Top pages
    • Top referrers
  2. Audiences

    • Device breakdown (mobile, desktop, tablet)
    • Browser usage
    • Operating systems
    • Geographic distribution
  3. Real-time

    • Live visitor count
    • Current popular pages
    • Recent events
  4. Web Vitals

    • LCP, INP, CLS scores
    • Performance over time
    • Device-specific metrics
  5. Custom Events

    • Event counts
    • Event properties
    • Conversion tracking

Limitations and pricing

Free tier:

  • 2,500 events/month
  • Basic analytics
  • 1 member

Pro tier ($10/member/month):

  • 100,000 events/month
  • Advanced filtering
  • Unlimited members
  • Data export

Enterprise:

  • Custom event limits
  • Dedicated support
  • SLA guarantees

Integration with Vercel Edge Config

You can dynamically control feature flags based on analytics:

// lib/feature-flags.ts
import { get } from '@vercel/edge-config';
import { track } from '@vercel/analytics';

export async function checkFeatureFlag(flagName: string): Promise<boolean> {
  const isEnabled = await get(flagName);

  // Track feature flag usage
  if (isEnabled) {
    track('Feature Flag Enabled', { flag: flagName });
  }

  return isEnabled || false;
}

Summary Vercel Analytics

In Quantum Metropolis 2150, where every millisecond matters, Vercel Analytics provides quantum precision in Next.js application monitoring:

Key advantages:

  • Zero-config setup for basic metrics
  • Automatic tracking of Core Web Vitals
  • Privacy-first approach (GDPR compliant)
  • Real-time data in the Vercel Dashboard
  • Integration with Vercel Edge Network
  • Custom events for business metrics

When to use Vercel Analytics:

  • Applications hosted on Vercel
  • You need privacy-first analytics
  • You want zero-config Web Vitals monitoring
  • Basic analytics is enough for your case
  • Budget allows for a paid plan for larger traffic

When to consider alternatives:

  • You need advanced user segmentation
  • You require funnel analysis and attribution modeling
  • You have very high traffic (> 1M page views/month)
  • You need integration with ad platforms
  • You prefer a self-hosted solution

Vercel Analytics is the ideal solution for most Next.js applications, offering an excellent balance between simplicity, performance, and functionality. Combined with Speed Insights, it creates a complete real-time application performance monitoring system!

Custom monitoring with Prometheus and Grafana

For more advanced monitoring, you can configure your own stack with Prometheus and Grafana.

1. Configuring Prometheus metrics

// lib/metrics.ts
import client from 'prom-client';

// Metrics registry
const register = new client.Registry();

// HTTP metrics
const httpRequestDuration = new client.Histogram({
  name: 'http_request_duration_seconds',
  help: 'Duration of HTTP requests in seconds',
  labelNames: ['method', 'route', 'status_code'],
  buckets: [0.1, 0.3, 0.5, 0.7, 1, 3, 5, 7, 10],
});

const httpRequestTotal = new client.Counter({
  name: 'http_requests_total',
  help: 'Total number of HTTP requests',
  labelNames: ['method', 'route', 'status_code'],
});

// Business metrics
const userRegistrations = new client.Counter({
  name: 'user_registrations_total',
  help: 'Total number of user registrations',
});

const ordersTotal = new client.Counter({
  name: 'orders_total',
  help: 'Total number of orders',
  labelNames: ['status'],
});

// Register metrics
register.registerMetric(httpRequestDuration);
register.registerMetric(httpRequestTotal);
register.registerMetric(userRegistrations);
register.registerMetric(ordersTotal);

// Add default Node.js metrics
client.collectDefaultMetrics({ register });

export {
  register,
  httpRequestDuration,
  httpRequestTotal,
  userRegistrations,
  orderTotal
};

2. Middleware for HTTP tracking

// middleware.ts
import { NextRequest, NextResponse } from 'next/server';
import { httpRequestDuration, httpRequestTotal } from '@/lib/metrics';

export function middleware(request: NextRequest) {
  const start = Date.now();

  // Continue processing the request
  const response = NextResponse.next();

  // Save metrics after processing the request
  response.headers.set('x-response-time', (Date.now() - start).toString());

  // Async metric saving (does not block the response)
  setImmediate(() => {
    const duration = (Date.now() - start) / 1000;
    const labels = {
      method: request.method,
      route: request.nextUrl.pathname,
      status_code: response.status.toString(),
    };

    httpRequestDuration.observe(labels, duration);
    httpRequestTotal.inc(labels);
  });

  return response;
}

export const config = {
  matcher: [
    '/((?!api|_next/static|_next/image|favicon.ico).*)',
  ],
};

3. Endpoint for Prometheus metrics

// app/api/metrics/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { register } from '@/lib/metrics';

export async function GET(request: NextRequest) {
  const metrics = await register.metrics();

  return new NextResponse(metrics, {
    headers: {
      'Content-Type': register.contentType,
    },
  });
}

Alerting and notifications

An important aspect of monitoring is automatic notification of problems.

1. Integration with Slack

// lib/alerts.ts
import { IncomingWebhook } from '@slack/webhook';

const webhook = new IncomingWebhook(process.env.SLACK_WEBHOOK_URL);

export async function sendSlackAlert(message: string, severity: 'info' | 'warning' | 'error') {
  const colors = {
    info: '#36a64f',
    warning: '#ffcc00',
    error: '#ff0000',
  };

  try {
    await webhook.send({
      attachments: [
        {
          color: colors[severity],
          fields: [
            {
              title: 'Alert',
              value: message,
              short: false,
            },
            {
              title: 'Time',
              value: new Date().toISOString(),
              short: true,
            },
            {
              title: 'Environment',
              value: process.env.NODE_ENV,
              short: true,
            },
          ],
        },
      ],
    });
  } catch (error) {
    console.error('Failed to send Slack alert:', error);
  }
}

// Function for checking thresholds and sending alerts
export function checkPerformanceThresholds(metrics: {
  lcp: number;
  inp: number;
  cls: number;
}) {
  if (metrics.lcp > 2500) {
    sendSlackAlert(`High LCP detected: ${metrics.lcp}ms`, 'warning');
  }

  if (metrics.inp > 200) {
    sendSlackAlert(`High INP detected: ${metrics.inp}ms`, 'warning');
  }

  if (metrics.cls > 0.1) {
    sendSlackAlert(`High CLS detected: ${metrics.cls}`, 'warning');
  }
}

2. Monitoring uptime

// lib/uptime-monitor.ts
import { sendSlackAlert } from './alerts';

interface HealthCheckResult {
  service: string;
  status: 'healthy' | 'unhealthy';
  responseTime: number;
  timestamp: Date;
}

export async function checkServiceHealth(url: string, service: string): Promise<HealthCheckResult> {
  const start = Date.now();

  try {
    const response = await fetch(url, {
      method: 'GET',
      timeout: 10000, // 10 second timeout
    });

    const responseTime = Date.now() - start;

    if (response.ok) {
      return {
        service,
        status: 'healthy',
        responseTime,
        timestamp: new Date(),
      };
    } else {
      await sendSlackAlert(`Service ${service} returned ${response.status}`, 'error');
      return {
        service,
        status: 'unhealthy',
        responseTime,
        timestamp: new Date(),
      };
    }
  } catch (error) {
    await sendSlackAlert(`Service ${service} is unreachable: ${error.message}`, 'error');
    return {
      service,
      status: 'unhealthy',
      responseTime: Date.now() - start,
      timestamp: new Date(),
    };
  }
}

// Function for running health checks
export async function runHealthChecks() {
  const services = [
    { name: 'Main App', url: 'https://your-app.com/api/health' },
    { name: 'Database', url: 'https://your-app.com/api/health/db' },
    { name: 'External API', url: 'https://api.external-service.com/health' },
  ];

  const results = await Promise.allSettled(
    services.map(service => checkServiceHealth(service.url, service.name))
  );

  results.forEach((result, index) => {
    if (result.status === 'fulfilled') {
      console.log(`Health check for ${services[index].name}:`, result.value);
    } else {
      console.error(`Health check failed for ${services[index].name}:`, result.reason);
    }
  });
}

Dashboard and data visualization

1. A simple dashboard in Next.js

// app/admin/monitoring/page.tsx
import { getWebVitalMetrics, getErrorMetrics } from '@/lib/analytics';
import { LineChart, BarChart } from '@/components/Charts';

export default async function MonitoringDashboard() {
  const webVitals = await getWebVitalMetrics();
  const errors = await getErrorMetrics();

  return (
    <div className="p-6">
      <h1 className="text-3xl font-bold mb-8">Monitoring Dashboard</h1>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
        {/* Core Web Vitals */}
        <div className="bg-white p-6 rounded-lg shadow">
          <h2 className="text-xl font-semibold mb-4">Core Web Vitals</h2>
          <LineChart
            data={webVitals}
            categories={['lcp', 'inp', 'cls']}
            xKey="timestamp"
          />
        </div>

        {/* Error Rate */}
        <div className="bg-white p-6 rounded-lg shadow">
          <h2 className="text-xl font-semibold mb-4">Error Rate</h2>
          <BarChart
            data={errors}
            category="count"
            xKey="hour"
          />
        </div>
      </div>

      {/* Real-time metrics */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <MetricCard title="Active Users" value="1,234" change="+5.2%" />
        <MetricCard title="Response Time" value="156ms" change="-2.1%" />
        <MetricCard title="Error Rate" value="0.01%" change="-50%" />
        <MetricCard title="Uptime" value="99.9%" change="+0.1%" />
      </div>
    </div>
  );
}

function MetricCard({ title, value, change }: {
  title: string;
  value: string;
  change: string;
}) {
  const isPositive = change.startsWith('+');
  const isNegative = change.startsWith('-');

  return (
    <div className="bg-white p-4 rounded-lg shadow">
      <h3 className="text-sm font-medium text-gray-500">{title}</h3>
      <div className="mt-2 flex items-baseline">
        <p className="text-2xl font-semibold text-gray-900">{value}</p>
        <p className={`ml-2 text-sm font-medium ${
          isPositive ? 'text-green-600' : isNegative ? 'text-red-600' : 'text-gray-500'
        }`}>
          {change}
        </p>
      </div>
    </div>
  );
}

Monitoring best practices

1. Sampling strategies

// lib/sampling.ts

// Function for determining whether an event should be tracked
export function shouldSample(sampleRate: number): boolean {
  return Math.random() < sampleRate;
}

// Adaptive sampling - more samples for errors
export function adaptiveSample(isError: boolean): boolean {
  return isError ? shouldSample(1.0) : shouldSample(0.1);
}

// Sampling based on user tier
export function userTierSample(userTier: 'free' | 'premium' | 'enterprise'): boolean {
  const rates = {
    free: 0.05,     // 5% for free users
    premium: 0.25,  // 25% for premium
    enterprise: 1.0, // 100% for enterprise
  };

  return shouldSample(rates[userTier]);
}

2. Monitoring performance optimization

// lib/performance-monitoring.ts

// Buffer for metrics - collect and send in batches
class MetricsBuffer {
  private buffer: any[] = [];
  private maxSize = 100;
  private flushInterval = 30000; // 30 seconds

  constructor() {
    // Automatic buffer flushing
    setInterval(() => this.flush(), this.flushInterval);
  }

  add(metric: any) {
    this.buffer.push(metric);

    if (this.buffer.length >= this.maxSize) {
      this.flush();
    }
  }

  private async flush() {
    if (this.buffer.length === 0) return;

    const metricsToSend = [...this.buffer];
    this.buffer = [];

    try {
      await fetch('/api/metrics/batch', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ metrics: metricsToSend }),
      });
    } catch (error) {
      console.error('Failed to send metrics batch:', error);
      // Return metrics to the buffer in case of error
      this.buffer.unshift(...metricsToSend);
    }
  }
}

export const metricsBuffer = new MetricsBuffer();

Summary

Performance monitoring and error analytics are key elements of any production Next.js application. A comprehensive monitoring approach includes:

  1. Error tracking - automatic detection and reporting of problems
  2. Performance monitoring - Core Web Vitals and other key metrics
  3. Alerting - immediate notifications about critical problems
  4. Dashboards - data visualization for decision-making
  5. User analytics - understanding how users use the application

When choosing monitoring tools, consider:

  • Sentry - for comprehensive error tracking
  • Vercel Analytics - for simple monitoring on Vercel
  • New Relic/DataDog - for advanced performance monitoring
  • Custom solutions - for specialized needs

Remember the balance between monitoring depth and impact on application performance. Use sampling, buffering, and optimize queries so that monitoring does not negatively affect user experience.

Code for this lesson: App.tsx
import React, { useState, useEffect } from 'react';

// Demo: Performance monitoring and error analytics
interface ErrorEntry {
  id: string;
  type: 'error' | 'warning' | 'info';
  message: string;
  stack: string;
  count: number;
  lastSeen: string;
  status: 'new' | 'acknowledged' | 'resolved';
}

interface PerformanceMetric {
  name: string;
  value: number;
  unit: string;
  status: 'good' | 'needs-improvement' | 'poor';
  threshold: { good: number; poor: number };
}

function MonitoringDemo() {
  const [errors, setErrors] = useState<ErrorEntry[]>([
    { id: '1', type: 'error', message: 'TypeError: Cannot read property of undefined', stack: 'at UserProfile (/app/components/UserProfile.tsx:42)', count: 23, lastSeen: '2 min ago', status: 'new' },
    { id: '2', type: 'error', message: 'NetworkError: Failed to fetch /api/data', stack: 'at fetchData (/app/lib/api.ts:15)', count: 8, lastSeen: '15 min ago', status: 'acknowledged' },
    { id: '3', type: 'warning', message: 'Large bundle size: chunk-vendors.js (450KB)', stack: 'Build warning', count: 1, lastSeen: '1 hour ago', status: 'new' },
    { id: '4', type: 'error', message: 'Hydration mismatch in <Header />', stack: 'at Header (/app/components/Header.tsx:18)', count: 156, lastSeen: '30 sec ago', status: 'new' },
  ]);

  const [metrics, setMetrics] = useState<PerformanceMetric[]>([
    { name: 'FCP', value: 1.2, unit: 's', status: 'good', threshold: { good: 1.8, poor: 3.0 } },
    { name: 'LCP', value: 2.4, unit: 's', status: 'needs-improvement', threshold: { good: 2.5, poor: 4.0 } },
    { name: 'CLS', value: 0.05, unit: '', status: 'good', threshold: { good: 0.1, poor: 0.25 } },
    { name: 'FID', value: 45, unit: 'ms', status: 'good', threshold: { good: 100, poor: 300 } },
    { name: 'TTFB', value: 320, unit: 'ms', status: 'needs-improvement', threshold: { good: 200, poor: 600 } },
    { name: 'INP', value: 180, unit: 'ms', status: 'needs-improvement', threshold: { good: 200, poor: 500 } },
  ]);

  const [activeTab, setActiveTab] = useState<'errors' | 'performance' | 'setup'>('errors');
  const [selectedTool, setSelectedTool] = useState<'sentry' | 'vercel' | 'custom'>('sentry');

  const statusColors: Record<string, string> = { good: '#10b981', 'needs-improvement': '#f59e0b', poor: '#ef4444' };
  const errorTypeColors: Record<string, string> = { error: '#ef4444', warning: '#f59e0b', info: '#3b82f6' };
  const errorStatusColors: Record<string, string> = { new: '#ef4444', acknowledged: '#f59e0b', resolved: '#10b981' };

  const updateErrorStatus = (id: string, status: ErrorEntry['status']) => {
    setErrors(prev => prev.map(e => e.id === id ? { ...e, status } : e));
  };

  const triggerError = () => {
    const newError: ErrorEntry = {
      id: String(Date.now()),
      type: 'error',
      message: ['RangeError: Maximum call stack', 'SyntaxError: Unexpected token', 'ReferenceError: x is not defined'][Math.floor(Math.random() * 3)],
      stack: 'at Component (/app/page.tsx:' + Math.floor(Math.random() * 100) + ')',
      count: 1, lastSeen: 'just now', status: 'new',
    };
    setErrors(prev => [newError, ...prev]);
  };

  const setupCode: Record<string, string> = {
    sentry: "// sentry.client.config.ts\nimport * as Sentry from '@sentry/nextjs';\n\nSentry.init({\n  dsn: process.env.SENTRY_DSN,\n  tracesSampleRate: 0.1,\n  replaysSessionSampleRate: 0.1,\n  integrations: [\n    Sentry.replayIntegration(),\n    Sentry.browserTracingIntegration(),\n  ],\n});",
    vercel: "// next.config.js\nmodule.exports = {\n  experimental: {\n    instrumentationHook: true,\n  },\n};\n\n// instrumentation.ts\nexport async function register() {\n  if (process.env.NEXT_RUNTIME === 'nodejs') {\n    // Server-side monitoring\n  }\n}",
    custom: "// lib/monitoring.ts\nexport function reportError(error: Error, context?: object) {\n  fetch('/api/errors', {\n    method: 'POST',\n    body: JSON.stringify({\n      message: error.message,\n      stack: error.stack,\n      context,\n      timestamp: Date.now(),\n    }),\n  });\n}",
  };

  return (
    <div style={{ background: '#0f0f23', minHeight: '100vh', padding: '20px', color: '#e0e0e0', fontFamily: 'system-ui' }}>
      <h1 style={{ color: '#64ffda', marginBottom: '8px' }}>Monitoring & Error Tracking</h1>
      <p style={{ color: '#8892b0', marginBottom: '24px' }}>Performance monitoring and error tracking in Next.js</p>

      <div style={{ display: 'flex', gap: '8px', marginBottom: '24px' }}>
        {[
          { id: 'errors' as const, label: 'Errors (' + errors.filter(e => e.status === 'new').length + ')' },
          { id: 'performance' as const, label: 'Performance' },
          { id: 'setup' as const, label: 'Setup' },
        ].map(tab => (
          <button key={tab.id} onClick={() => setActiveTab(tab.id)} style={{
            padding: '10px 20px', borderRadius: '8px', border: 'none', cursor: 'pointer',
            background: activeTab === tab.id ? '#64ffda' : '#1a1a2e', color: activeTab === tab.id ? '#0f0f23' : '#8892b0', fontWeight: 'bold',
          }}>{tab.label}</button>
        ))}
      </div>

      {activeTab === 'errors' && (
        <div>
          <button onClick={triggerError} style={{ padding: '8px 16px', borderRadius: '6px', background: '#ef4444', color: '#fff', border: 'none', cursor: 'pointer', marginBottom: '16px' }}>
            Simulate error
          </button>
          <div style={{ display: 'grid', gap: '8px' }}>
            {errors.map(err => (
              <div key={err.id} style={{ padding: '14px', borderRadius: '8px', background: '#1a1a2e', border: '1px solid #333' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                    <span style={{ fontSize: '11px', padding: '2px 8px', borderRadius: '12px', background: errorTypeColors[err.type] + '30', color: errorTypeColors[err.type] }}>{err.type}</span>
                    <span style={{ fontSize: '11px', padding: '2px 8px', borderRadius: '12px', background: errorStatusColors[err.status] + '30', color: errorStatusColors[err.status] }}>{err.status}</span>
                    <span style={{ fontSize: '12px', color: '#8892b0' }}>x{err.count} | {err.lastSeen}</span>
                  </div>
                  <select value={err.status} onChange={e => updateErrorStatus(err.id, e.target.value as any)} style={{ padding: '4px 8px', borderRadius: '4px', background: '#0f0f23', color: '#fff', border: '1px solid #333', fontSize: '11px' }}>
                    <option value="new">New</option>
                    <option value="acknowledged">Acknowledged</option>
                    <option value="resolved">Resolved</option>
                  </select>
                </div>
                <div style={{ color: errorTypeColors[err.type], fontWeight: 'bold', fontSize: '14px' }}>{err.message}</div>
                <div style={{ fontSize: '12px', color: '#555', marginTop: '4px' }}>{err.stack}</div>
              </div>
            ))}
          </div>
        </div>
      )}

      {activeTab === 'performance' && (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '16px' }}>
          {metrics.map(m => (
            <div key={m.name} style={{ background: '#1a1a2e', padding: '20px', borderRadius: '12px', border: '1px solid #333', textAlign: 'center' }}>
              <div style={{ fontSize: '32px', fontWeight: 'bold', color: statusColors[m.status] }}>{m.value}{m.unit}</div>
              <div style={{ fontSize: '16px', color: '#64ffda', marginTop: '4px' }}>{m.name}</div>
              <div style={{ fontSize: '12px', color: statusColors[m.status], marginTop: '4px' }}>{m.status.replace('-', ' ')}</div>
              <div style={{ marginTop: '8px', height: '4px', background: '#333', borderRadius: '2px', overflow: 'hidden' }}>
                <div style={{ width: Math.min(100, (m.value / m.threshold.poor) * 100) + '%', height: '100%', background: statusColors[m.status] }} />
              </div>
              <div style={{ fontSize: '10px', color: '#555', marginTop: '4px' }}>Good: &lt;{m.threshold.good}{m.unit} | Poor: &gt;{m.threshold.poor}{m.unit}</div>
            </div>
          ))}
        </div>
      )}

      {activeTab === 'setup' && (
        <div>
          <div style={{ display: 'flex', gap: '8px', marginBottom: '16px' }}>
            {[
              { id: 'sentry' as const, label: 'Sentry' },
              { id: 'vercel' as const, label: 'Vercel Analytics' },
              { id: 'custom' as const, label: 'Custom' },
            ].map(tool => (
              <button key={tool.id} onClick={() => setSelectedTool(tool.id)} style={{
                padding: '8px 16px', borderRadius: '8px', border: 'none', cursor: 'pointer',
                background: selectedTool === tool.id ? '#7c3aed' : '#1a1a2e', color: '#fff',
              }}>{tool.label}</button>
            ))}
          </div>
          <pre style={{ background: '#1a1a2e', padding: '16px', borderRadius: '8px', fontSize: '12px', overflow: 'auto', border: '1px solid #333', color: '#e0e0e0', whiteSpace: 'pre-wrap' }}>
            {setupCode[selectedTool]}
          </pre>
        </div>
      )}
    </div>
  );
}

export default MonitoringDemo;

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Which Core Web Vitals metrics does Google use to evaluate page performance?

Hands-on tasks in the game

  • Code editor

    Create an application monitoring system: performance metrics, error tracking, uptime monitoring using Web Vitals

  • Vertical ordering

    Arrange the elements in the correct order: Choose tool โ†’ Add instrumentation โ†’ Set up dashboards

  • Vertical ordering

    Arrange the performance budget configuration steps in the correct order:

  1. Coding taskPractice: Create an Application Monitoring System
  2. Put in orderSequence: Choose tool โ†’ Add instrumentation โ†’ ...
  3. QuestionApplication Performance Monitoring
  4. Put in orderSequence: Define metrics โ†’ Measure baseline โ†’ Set limits

Useful articles