Blog>
Snippets

Client-Side Navigation Timing

Use Next.js Router events to instrument the client-side routing performance and measure page transition times.
import Router from 'next/router';

let perfStart = 0;

// Measure time taken for a page transition
class NavigationTimer {
  constructor() {
    Router.events.on('routeChangeStart', this.handleRouteChangeStart);
    Router.events.on('routeChangeComplete', this.handleRouteChangeComplete);
  }

  handleRouteChangeStart = (url) => {
    console.log(`Starting navigation to ${url}`);
    perfStart = performance.now(); // mark the start of the navigation
  };

  handleRouteChangeComplete = (url) => {
    const duration = performance.now() - perfStart;
    console.log(`Navigation to ${url} took ${duration}ms`); // compute and log the time taken
    // Send the duration and URL to an analytics endpoint or use for real-time monitoring
    // e.g. sendNavigationTiming(duration, url);
  };
}

const navigationTimer = new NavigationTimer();
This code listens to Next.js router events to start and stop a timer for navigation performance. When the route starts changing, `routeChangeStart` is fired and the timer starts, and when the route finishes changing, `routeChangeComplete` is fired and the timer stops. The duration of the page transition is then logged.