Blog>
Snippets

Server-Side Render Timing

Instrument a Next.js page with server-side render timing to trace the performance of the initial render.
import { useEffect } from 'react';

export async function getServerSideProps(context) {
  const start = process.hrtime.bigint(); // Start timing
  // Perform initial data fetching or other server-side logic here

  const end = process.hrtime.bigint(); // End timing
  const diff = end - start; // Calculate the difference in nanoseconds
  console.log(`Render time: ${diff / BigInt(1e6)}ms`); // Convert to milliseconds and log it
  
  // Your usual getServerSideProps return
  return {
    props: {}, // Your props
  };
}
This code sets up server-side render timing inside the getServerSideProps function in a Next.js page component. It uses process.hrtime.bigint to obtain high-resolution timestamps before and after the server-side logic, calculates the difference to get the render time in milliseconds, and logs it to the console.